unity how to make look at mouse code example

Example 1: how to make an object point towards the mouse in unity

//Inside your update loop, add the following code:

//First, get the mouse position
Vector2 mousePosition = new Vector2 ( 
  Input.GetAxis("MouseX"), 
  Input.GetAxis("MouseY")
);
//Then, use unity's built-in lookAt function to do all the math for you:
transform.LookAt(mousePosition);

Example 2: unity player look at mouse

private void Update()
    {
        Vector3 mousePos = Input.mousePosition;
        mousePos.z = 5.23f;

        Vector3 objectPos = UnityEngine.Camera.main.WorldToScreenPoint(transform.position);
        
        mousePos.x = mousePos.x - objectPos.x;
        mousePos.y = mousePos.y - objectPos.y;

        float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle - 90));
    }