1

In Unity, I have

public enum inven {Food,Scissors,Nothing};
public inven held;

How can I access the enum and, more importantly, the information contained in the held variable, from another script. I tried the Singleton Method:

public class Singleton : MonoBehaviour {

    public static Singleton access;
    public enum inven {Nothing, Scissors, Food};
    public inven held;

    void Awake () {
    access = (access==null) ? this : access;
    }
}

to make global variables, accessed by

Singleton.inven.food //or
Singleton.access.held //respectively

However, that returned "Null reference exception: Object reference not set to an instance of an object." I also tried using this:

public class Accessor : MonoBehaviour {
    void Start() {
        GameObject HeldItem = GameObject.Find("Story"); //where story is the Gameobject containing the script of the enum and variable
        TextController textcontroller = Story.GetComponent<Textcontroller>(); //Where TextController is the sript containing the enum and variable
    }
}

accessed by TextController.held etc, returned that it needed an object reference. What is the proper way of doing this?

1

1 Answer 1

1

Here's how I do my singletons. In my case, it's called SharedData.

using UnityEngine;
using System.Collections;

public class Booter : MonoBehaviour
{
    void Start ()
    {
        Application.targetFrameRate = 30;
        GameObject obj = GameObject.Find("Globals");
        if(obj == null)
        {
            obj = new GameObject("Globals");
            GameObject.DontDestroyOnLoad(obj);
            SharedData sharedData = obj.AddComponent<SharedData>();
            sharedData.Initialize();
        }
    }
}

This script is attached to an object in the first scene that loads, and it is set in the script execution order to go first. It creates a GameObject to attach the SharedData component to, then tells the engine not to delete that GameObject when new levels are loaded.

Then to access it, I do this:

public class Interface : MonoBehaviour
{
    private SharedData m_sharedData;

    public void Initialize()
    {
        GameObject globalObj = GameObject.Find("Globals");
        m_sharedData = globalObj.GetComponent<SharedData>();

        m_sharedData.LoadData(); // This is where I use something on the singleton.
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.