(SOLVED) Accessing (string) arrays by enumerations from another class
Edit: I figured it out, I was instancing the class in Start() rather than Awake() and it was called too soon to exist.
Hello, first post; hopefully this goes to the correct forum. I've been slowly learning Unity, however I'm quite new to C# as well, so there's a fair change my code has mistakes or general weirdness. Feel free to point out any of those.
What I'm trying to do: Have a class that contains a string array accessible from other classes, using related enumerations as array indexes to point to the correct strings.
Or, put simpler, I want a list of integers that always point to the same thing, and also have a string value (eg. filename) associated with them that I can access.
Here's a stripped down example of what I have thus far:
// This class holds info I want to access from elsewhere. Connected to a separate gameobject.
public class StuffToAccess : MonoBehaviour {
public static StuffToAccess instance;
// I am a singleton
void Awake() {
if (instance == null) {
instance = this;
DontDestroyOnLoad(instance);
} else {
Destroy(this);
}
}
public enum TESTING {
FIRST = 0,
SECOND,
THIRD,
ENUM_COUNT
};
public string[] strings = new string[(int)TESTING.ENUM_COUNT] {
"First String",
"Second String",
"Third String"
};
}
// This is the class that wants to access the one above
public class ThingThatNeedsAccess : MonoBehaviour {
void Start() {
//Test 1
Debug.Log( "String contents: " + StuffToAccess.instance.strings[0] );
// Test 2, what I was looking to do (is there a nicer way to achieve this?)
Debug.Log( "String contents: " + StuffToAccess.instance.strings[ (int)StuffToAccess.TESTING.FIRST ] );
}
}
However, this gives me the following error: "NullReferenceException: Object reference not set to an instance of an object"
What am I doing wrong here in terms of syntax / design in general? There's probably some better way to do this that I'm not seeing. Thanks for your time.
Your answer
Follow this Question
Related Questions
C# Find specific object by getting one of its variables 0 Answers
Custom class, Null Reference Exception 4 Answers
How to get the component in a new class 0 Answers
Assigning to array give NullReferenceExecption!?!! 0 Answers
Nested for loop isnt working 1 Answer