Search Unity

How to rotate camera and player C#

Discussion in 'Scripting' started by WADEY216, Sep 20, 2021.

  1. WADEY216

    WADEY216

    Joined:
    Sep 20, 2021
    Posts:
    2
    Hi there, I want to move my camera and my player simultaneously within the same script using EulerAngles, however if I assign transforms like so: "Transform player = GameObject.FindGameObjectWithTag("Player").transform;" and then i call it with eulerangles like so: "player.eulerAngles = player.eulerAngles - (rotation * sensitivity);". Visual studios then tells me that "The name player does not exist in current context", how do i fix this?
    Full code:
    Code (CSharp):
    1. public class CameraController : MonoBehaviour
    2. {
    3.     public float sensitivity = 2.0f;
    4.     public float X;
    5.     public float Y;
    6.     public Vector3 rotation;
    7.  
    8.     void Start()
    9.     {
    10.         Transform player = GameObject.FindGameObjectWithTag("Player").transform;
    11.         Transform mainCamera = GameObject.FindGameObjectWithTag("MainCamera").transform;
    12.     }
    13.  
    14.     void Update()
    15.     {
    16.         X = Input.GetAxis("Mouse Y");
    17.         Y = Input.GetAxis("Mouse X");
    18.  
    19.         Vector3 rotation = new Vector3 (X, -Y, 0);
    20.         transform.eulerAngles = transform.eulerAngles - (rotation * sensitivity);
    21.         player.eulerAngles = player.eulerAngles - (rotation * sensitivity);
    22.     }
    23. }

    **X and Y are flipped because for some reason if they are set normally, moving the mouse left and right rotates the camera up and down.
     
    Last edited: Sep 20, 2021
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,686
    Line 10 makes a local variable, as does Line 11.

    Nobody outside of Start() can see those variables.

    Instead, make a class variable (like your top variables), then do the find operations in Start(), removing the type declaration from those lines.