Member 'Camera.main' cannot be accessed with an instance reference; qualify it with a Type name instead

Viewed 744

Here is my line of code:

GetComponent<Camera>().main.transform.position.y = StaticCameraY;

This is the error that I get and I am not sure how to solve it:

Member 'Camera.main' cannot be accessed with an instance reference; qualify it with a Type name instead

1 Answers

Access the main camera like :

Camera.main.transform.position = new Vector3(Camera.main.transform.position, StaticCamera.y, Camera.main.transform.position.z);

For the following reasons:
- When using GetComponent to get a camera on your current gameObject, you have to use it like Camera cam = gameObject.GetComponent<Camera>();With no need to call it main. You do have to pass the type of component you are getting in <> though.
- The main camera can be found with Camera.main with no GetComponent involved.
- You can't set individual elements of transform.position. You have to set the whole Vector3. To do this we pass the current transform.position.x and transform.position.z and update only the y because that's the one you care about changing.

Hope that helped.

Related