Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

get_main is not allowed to be called from a MonoBehaviour constructor

Discussion in 'Scripting' started by Abdou23, Jan 22, 2017.

  1. Abdou23

    Abdou23

    Joined:
    May 2, 2014
    Posts:
    77
    I'm using Visual Studio Code on Mac and IntelliSense is working fine. I get this error:
    Code (csharp):
    1. get_main is not allowed to be called from a MonoBehaviour constructor
    On this line:
    Code (csharp):
    1.     private Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    2.  
     
    OyeSpeedy likes this.
  2. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    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.
     
    OyeSpeedy and poiuminaj like this.
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,380
    when defining a field, if you have initialization code...

    this part:
    Code (csharp):
    1. =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.

    Code (csharp):
    1.  
    2. private Ray ray;
    3.  
    4. void Start()
    5. {
    6.     ray =Camera.main.ScreenPointToRay(Input.mousePosition);
    7. }
    8.  
     
    OyeSpeedy, Abdou23 and Polymorphik like this.
  4. Abdou23

    Abdou23

    Joined:
    May 2, 2014
    Posts:
    77
    Thanks guys.