Hi everyone!
I’m trying to access a list located in a script(a singleton with a generic instance of the type of the class), from other scripts, but i can’t figure a way to do it.
GameManager is the class which contains the list, List is the list(dunno if there is any difference in accessing different kinds of list) and instance is the generic type instance(in this case GameManager type)
As of now I tried
GameManager.List (Doesn’t work)
GameManager.instance.List ( gives me this error :
NullReferenceException: Object reference not set to an instance of an object)
I have also instanstiated the List in GameManager
GameManager List=new List();
Of course I know already the sintax to instantiate a Dictionary instead of an Hashset insted of an array, so that is not the problem.
Thank you! I hope my explanation of the problem will be clear enough. 
Naming a variable “List” does not make it a List.
public List<float> ListOfFloats;
void Awake()
{
ListOfFloats = new List<float>();
ListOfFloats.Add(1);
ListOfFloats.Add(12);
ListOfFloats.Add(15);
ListOfFloats.Add(34);
}
void Start()
{
Debug.Log(ListOfFloats.Count + " (List count)");
foreach (var x in ListOfFloats)
{
Debug.Log("List Item: " + x);
}
}
As I said, I know it already. I have already created a lot of perfectly-working lists and LIst was just an example “replace with desired list type”
I’m just asking how can I modify the list(by adding or removing members) from a different script.
The same way you reference everything else across components/classes. Obtain some sort of reference to the class or component, then access it directly.
public class SomeManagerClass : MonoBehaviour
{
public List<float> ListOfFloats;
void Awake()
{
ListOfFloats = new List<float>();
ListOfFloats.Add(1);
ListOfFloats.Add(12);
ListOfFloats.Add(15);
ListOfFloats.Add(34);
}
}
public class Fubar : MonoBehaviour
{
public SomeManagerClass MyOtherClass; // drag something into this field in the inspector.
void Start()
{
MyOtherClass.ListOfFloats.Add(99);
foreach (var x in MyOtherClass.ListOfFloats)
{
Debug.Log("List Item: " + x);
}
}
}
1 Like
I hoped for an easier way but ur explanation is probably the best one to preserve the OOP fundamentals. Thank you 