user4756068
user4756068

Reputation:

Why am I getting a NullReferenceException when my variable is instantiated in the "awake" method?

I keep getting this error when I click the Card so I can move it.

NullReferenceException: Object reference not set to an instance of an object CardProspector.OnMouseUpAsButton () (at Assets/__Scripts/CardProspector.cs:17) UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32, Int32)

The exception indicates the following method in my CardProspector class:

override public void OnMouseUpAsButton() {
    Prospector.S.CardClicked(this);  // line 17
    base.OnMouseUpAsButton();
}

But that variable should have been instantiated by my Prospector class, the relevant portion of which is shown below:

public class Prospector : MonoBehaviour {
    static public Prospector S;
    ...
    ...

    // Use this for initialization
    void awake() {
        S = this;
    }

    ...
    ...
}

Upvotes: 1

Views: 144

Answers (2)

Russ
Russ

Reputation: 4173

This part of the message gives away where the problem is:

(at Assets/__Scripts/CardProspector.cs:17)

That ":17" means line 17 of your CardProspector.cs file, which translates to the following line:

Prospector.S.CardClicked(this);

That would suggest that static property "S" is null--it hasn't been defined.

Since "S" is defined in method Awake(), you need to call Awake() before you reference property "S" in any way.

Upvotes: 0

jan
jan

Reputation: 875

Awake() is case sensitive and will never be called in your code.

Upvotes: 3

Related Questions