简体   繁体   中英

Accessing a Singleton returns (NullReferenceException)

i feel stupid really, but i think i am being snow blind. i cannot access a singleton class method when calling from another classy. i get the dreaded

(NullReferenceException).

here are both my simple singleton and how i am calling the method.

public class PlayerNodePosition : MonoBehaviour 
{

public static PlayerNodePosition instance;

string code;

void Awake()
{
    if (instance == null)
    {
        Debug.LogWarning("More than one instance of Inventory found!");
        return;
    }

    instance = this;
}

public void AddCode(string _code)
{
    code = _code;
}
}

and here is the caller from another script.

void AddCode()
{

    PlayerNodePosition.instance.AddCode("Added!");

}

being a "simpleton" i am obviously missing the obvious.

You don't instantiate instance anywhere. You would need something like

private static PlayerNodePosition playerNodePosition;
public static PlayerNodePosition instance
{
    get 
    {
        if (playerNodePosition == null) {
            playerNodePosition = new PlayerNodePosition();
        }
        return playerNodePosition;
    }
}

The method Awake should be static and the instance should be set. I have no chance to check whether this runs as I have no C# installed, but the Debug log warning you give is logically wrong. If there is no instance, you need to create one. If there is an instance, you return that one. This is the singleton pattern.

public class PlayerNodePosition : MonoBehaviour 
{
    public static PlayerNodePosition instance;

    string code;

    void static getInstance()
    {
        if (instance == null)
        {
            instance = new PlayerNodePosition();
        }

        return instance;
    }

    public void AddCode(string _code)
    {
        code = _code;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM