get_main is not allowed to be called from a MonoBehaviour constructor

I’m using Visual Studio Code on Mac and IntelliSense is working fine. I get this error:

get_main is not allowed to be called from a MonoBehaviour constructor

On this line:

    private Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
1 Like

When initializing members they must be constant values. Camera.main does not guarantee a constant value therefore you cannot call it there. Use Awake or Start for that.

2 Likes

when defining a field, if you have initialization code…

this part:

=Camera.main.ScreenPointToRay(Input.mousePosition)

Then that code is actually ran when the object is constructed (hence “in the constructor”).

You’re not allowed to access certain parts of the unity API while the object is constructed. Because of the way that unity creates objects, the unity API could be in an unsuitable state to access it, so it blocks you accessing it.

Instead put that code in the Start/Awake method.

private Ray ray;

void Start()
{
    ray =Camera.main.ScreenPointToRay(Input.mousePosition);
}
3 Likes

Thanks guys.