- Home /
How to get a List of references of instances in a static variable
I want a parent class to contain a static LinkedList with all Instances of the class so I can manipulate or search them all at once. Unfortunately I do not understand Unity enough yet to get this to work.
This is an example of what I am trying to do. I tried using gameObject instead of Character and even GetComponent() returns a nullpointer exception.
public abstract class Character : MonoBehaviour {
public static LinkedList<Character> characters;
void Start () {
ChildStart();
RegisterCharacter(this as Character);
}
public static void RegisterCharacter(Character c)
{
characters.AddLast(c);
Debug.Log("Registred " + c.name);
}
}
Can anyone help me please? Thank you :)
What does ChildStart()
do? It seems you are not initializing your characters
list.
Answer by ElijahShadbolt · Feb 05, 2018 at 12:20 AM
Your characters
list could be null.
public static LinkedList<Character> characters = new LinkedList<Character>();
To avoid this error generally: before you try to access any object's members (like AddLast), check that it is not null.
if (characters == null)
characters = new LinkedList<Character>();
characters.AddLast(c);
if (characters != null) {
characters.AddLast(c);
}
else
Debug.LogError("Reference is null!");
Wow this was so stupid, I can't believe I didn't notice this my self, thank you
Your answer
Follow this Question
Related Questions
Weird problem with referencing game manager 1 Answer
How do you reference different cameras 2 Answers
gameObject are not referenced 2 Answers
How to get a referance to an instantiated prefab clone ? 1 Answer
Setting refrences in a script 2 Answers