Global List variable problem

I have a Data. cs in the asset folder:

public class Data
{
public const int robotMax = 10;
    public static List<Robot> robotAll = new List<Robot>();
}
public class Robot
{
    public int uniqueID;
}

And i have a gameobject with following function:

 void SaveRobot()
    {
        int i;
        Robot robot = new Robot();

        for ( i = 0; i < Data.robotMax; i++)
        {           
            robot.uniqueID = i;          
            Data.robotAll.Add(robot);
            print(Data.robotAll[i].uniqueID);
       
        }
        for(i=0;i<Data.robotAll.Count;i++)
        print(Data.robotAll[i].uniqueID);
}

The problem is the uniqueID of robotAll are all 9 in the 2nd for loop, but the 1st loop show they are 1,2,3…9, the correct number i expected.

I dont know why.

This happens because you are always changing “robot” id, you are never actually instantiating a new robot. At the end of your first cycle, Data.robotAll will contain a reference to the same instance of robot nine times, but you won’t notice it because of course you are printing only the last element every time. Try to move robot declaration (line 4) down to line 8, it should fix the problem :slight_smile: