Own Class and List<> problems Unity C#

I need your help with things that are going to blow up my mind...(Don't know why but I can't write "Hello everybody!" at the start of the post. Forum hides it:)

I can't figure out why my List <'My Tile Class> is cleared by itself.

I have few prefabs (with box-collider) with no scripts attached to them and one script on the scene. The idea is to take random prefab, attach random value to it and initiate it. After that player clicks on prefab on the scene and gets its value.

public class Generate_Field : MonoBehaviour {

    public class Tiles {
        public GameObject My_Tile;
        public int My_Value;

public List<Tiles> My_List;
private GameObject EmptyObj;
// ... other variables

void Start (){
List<Tiles> My_List = new List<Tiles> ();
// ... below some calculation (about 100 rows)

//Instantiate obj and give its reference to Emptyobj
EmptyObj = Instantiate (My_GameObj_To_Inst, new Vector3(My_X, My_Y, 0f), Quaternion.identity);

Tiles Tile1 = new Tiles ();
Tile1.My_Tile = EmptyObj;
Tile1.My_Value = 1; //
My_List.Add (Tile1); // Add Tile1 (with reference to Gameobj and value to List) 

// If I put code inside Void Start () it works ok and print all values
        foreach (Tiles SS in My_List) {
            print (SS.My_Value);

The problem is when I put it to Void Update ().

My_List somehow "Suicide" to zero.count although it is public List. In that case I get error: "NullReferenceException: Object reference not set to an instance of an object..."

void Update ()
    if (Input.GetKeyDown (KeyCode.Mouse1)) {
print (My_List.Count);

1 answer

  • answered 2020-03-31 09:36 artcorpse

    You declare a new local list in Start and populate that one. If you mean to initialise the class member, remove the type from the line doing the initialisation.

    void Start (){
        My_List = new List<Tiles> (); // class member, not new variable.

    As a usual guideline, it's better to initialise lists at the declaration point. There's usually no reason to replace the list at a later time.