UnityException: You are not allowed to call this function when declaring a variable.

Hi all,

Code

 public static FPSCoordinator instance
        {
            get
            {
                if (m_instance == null)
                {
     m_instance = GameObject.Find( "FPSCoordinator" ).GetComponent<FPSCoordinator>();
     m_instance.m_photonView = m_instance.gameObject.GetComponent<PhotonView>();
                }
    
                return m_instance;
            }
        }

ERROR

UnityException: You are not allowed to call this function when declaring a variable.
Move it to the line after without a variable declaration.
If you are using C# don't use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function.
FPSCoordinator.get_instance () (at Assets/2-Scripts/NetworkFramework/FPSCoordinator.cs:127)
FPSCamera..ctor ()

i am getting the error listed above in the given line

m_instance = GameObject.Find( "FPSCoordinator" ).GetComponent<FPSCoordinator>();

can anyone please help me out in solving this error.

You need to initialize that variable in Awake or later. I’m guessing something accesses that Iinstance property too early in the Unity cycle. You would be better off having a script attached to the object that sets the instance variable in Awake.

Just to make the answers in this post more complete.
In C# I ran into this problem when combining normal C# classes with MonoBehaviour classes. To make it more performance I used C# classes but whenever you instantiate a MonoBehaviour class indirectly from within a constructor of a normal C# class I got this error.

For me that happened with the singleton pattern:

public static Thing Instance(
if(instance == null){
GameObject go = new GameObject();
instance = go.AddComponent();

if I then need the Instance for the first time in a constructor of a normal C# class. I get the same error which points to the go.AddComponent() line, in that case of course I can’t initialize the variable later since the Start will never be executed if I don’t add the component. So basically I learned my lesson not to use plain C# classes for performance reasons…