Question

I have a singleton:

private static MyClass instance;

public static MyClass Instance
{
    get
    {
        if (instance == null)
        {
            GameObject go = GameObject.Find("MyClassObject");

            if(go == null)
            {
                Debug.LogError("Can not found MyClassObject!");
            }

            instance = go.GetComponent<MyClass>();
        }

        return instance;
    }
}

void Awake()
{
    MakePhotoState.Instance;   // 1
}

At 1 I'd like to call the Instance getter which would create the instance for my singleton. Awake is actually a MonoBehaviour method (Unity3D stuff) but I don't think that's important here.

Code at 1 gives me the following error:

error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

whose meaning I understand but it shouldn't apply here - I'm calling (implicitly) the Instance getter.

One workaround I can think of would be to assign the result of 1 to a local dummy variable but that's a bad solution IMO.

Is there any way to call get explicitly? If not, how do I make the error go away?

Was it helpful?

Solution

Property accessors aren't quite the same thing as method calls. Try moving your init code into a static constructor, and letting the Instance getter just return the (private static readonly) singleton instance.

The plus is that the static constructor will automatically be executed for you before any interaction with that class occurs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top