List is created correctly in Start() but returns size 0 in play mode

Hello, I am fairly new to Unity and have limited experience with C#, I have been struggling with this problem for a couple of days and was not able to find a solution on forum.

I have a list “Matrix” that is being created in runtime. When GetList() is called from Start(), the Debug.Log shows correctly the size of the list.
But if I call GetList() from another class or I try to access the list in anyway in play mode, the size count of the list is always 0 and I cannot access the list items (of course).

I need to access this list during play mode to retrieve and update values dynamically… but I can’t since the it seems to reset to size 0 during play mode.

Curiously, if I create a list of strings visible in the inspector and populate it in runtime, the list looks full and all items are there in the inspector… while if I call .count in runtime returns 0 once again, and once again I cannot access list values from script.

Not sure what I am doing wrong, any help is appreciated. Thanks

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class HexGrid : MonoBehaviour {

public int gridSizeX;
public int gridSizeY;

public List<HexID> Matrix = new List<HexID>();

public class HexID
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int X { get; set; }
    public int Y { get; set; }
    public bool Active { get; set; }
}

void Start()
{
    Matrix = CreateMatrix();
    GetList();
}

public List<HexID> CreateMatrix()
{
    int ID = 0;
    for (int y = 0; y < gridSizeY; y++)
    {
        for (int x = 0; x < gridSizeX; x++)
        {
            Matrix.Add(new HexID() { ID = ID, Name = "(" + x + ", " + y + ")", X = x, Y=y, Active = false });
            MatrixX.Add(ID);
            ID++;
        }
    }
    return Matrix;
}

 public List<HexID> GetList()
{
    Debug.Log("Matrix size is  " + Matrix.Count);
    return Matrix;
}

}

Try Moving assignment of the list “Matrix” to the Awake() method instead of Start() cause it looks like you call your list before Start() method in HexID class has done the assignment

Thanks for reply; I used Awake with no results; looks like that by adding

 void Update() { if (Input.GetKeyDown(KeyCode.A)) GetListCount(); }
 public void GetListCount() { Debug.Log("Matrix size is " + Matrix.Count); }

the returned value is correct, but I can’t manage to call GetListCount() from another class.

I have been trying to restructure my code, but the problem persists…
Right now, I have class HexGrid attached to a GameObject, in additon to create the Matrix the script arrenges a prefab into a Hexagonal Grid. I have attached to this prefab a Controller Class that calls the size of the matrix onMouseDown… but it keeps returning zero.

is there maybe something wrong with my hierarchy? I am posting the whole code to provide as many info as possible. Thanks all for helping.
I have arranged the code that creates the matrix into another class file =>

using System.Collections.Generic;
namespace Pasquale.CSharp {

public class MatrixData
{

    public List<HexID> Data= new List<HexID>();;

    public class HexID
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int X { get; set; }
        public int Y { get; set; }
        public bool Active { get; set; }
    }

    public MatrixData(int gridSizeX, int gridSizeY)
    {
         
        int ID = 0;
        for (int y = 0; y < gridSizeY; y++)
        {
            for (int x = 0; x < gridSizeX; x++)
            {
                Data.Add(new HexID() { ID = ID, Name = "(" + x + ", " + y + ")", X = x, Y = y, Active = false });
                ID++;
            }
        }
    }
}
}

== HexGrid Is Attached to an Empty GameObject and a sprite prefab (a hexagonal tile) is attached to HexGrid ===

using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using Pasquale.CSharp;

public class HexGrid : MonoBehaviour {

public int gridSizeX;
public int gridSizeY;
public float hexWidth;
public float hexHeight;
public float gap = 0;
MatrixData Matrix;

Vector2 startPos;
public Transform HexPrefab;

void Start()
{
    AddGap();
    CalcStartPos();
    Matrix = new MatrixData(gridSizeX, gridSizeY);
    CreateGrid();
}

void AddGap()
{
    hexWidth += hexWidth + gap;
    hexHeight += hexHeight + gap;
}

void CalcStartPos()
{
    float offset = 0;
    if (gridSizeY / 2 % 2 != 0)
        offset = hexWidth / 2;
    float x = -hexWidth * (gridSizeX / 2) - offset;
    float y = hexHeight * 3 / 4 * (gridSizeY / 2);
    startPos = new Vector2(x,y);
}

Vector2 CalcWorldPos(Vector2 gridPos)
{
    float offset = 0;
    if (gridPos.y % 2 != 0) 
        offset = hexWidth / 2;

    float x = startPos.x + gridPos.x * hexWidth + offset;
    float y = startPos.y - gridPos.y * hexHeight * 3 / 4;

    return new Vector2(x, y);
}

void CreateGrid()
{
    foreach (MatrixData.HexID item in Matrix.Data)
    {
        Transform hex = Instantiate(HexPrefab) as Transform;
        Vector2 gridPos = new Vector2(item.X, item.Y);
        hex.position = CalcWorldPos(gridPos);
        hex.transform.SetParent(this.transform);
        hex.name = item.Name;
    }
}

void Update() { if (Input.GetKeyDown(KeyCode.A)) GetListCount(); }

public void GetListCount() { Debug.Log("Matrix size is " + Matrix.Data.Count); }

public void SetStatus(string name, bool status) { Matrix.Data.Where(d => d.Name == name).First().Active = status; }

public List<MatrixData.HexID> GetList() { return Matrix.Data; }

}

======this class is attached to the hexagonal tile prefab… I am trying to access the matrix to manipulate its data=====

public class Controller:MonoBehaviour {

public GameObject HexTile;
public List<MatrixData.HexID> gridController = new List<MatrixData.HexID>();

private void OnMouseDown()
{
    
    Debug.Log(HexTile.name);
    Debug.Log(gridController.Count);
     
}
}

Thanks again!

Declare a public static variable of HexGrid in your HexGrid-Class and assign it in Awake()

public static HexGrid instance; 
void Awake(){
   HexGrid.instance = this;
}

Now you can access HexGrid from anywhere with:

HexGrid.instance.CallYourFunction();

This works aslong you only have one HexGrid in your entire scene! It won’t work when there are more than one.

Otherwise you have to use something like

YourHexGridGameObject.GetComponent<HexGrid>().CallYourFunction();