- Home /
how to add game object to custom class with for loop
I'm trying to add a series of game objects to my list, but when I add them only one prefab is added to list the number of times I want. When I debug it, it shows the names of all the prefabs I wanted but doesn't add them to the list.
//the list of game pieces
public List<pieceList> piecesList = new List<pieceList>();
void Start()
{
//for the components/vaibles in my custom class
pieceList pieceInfo = new pieceList();
//this instantiates the game pieces
for (int i = 0; i < 2; i++)
{
pieceInfo.gPiece = (GameObject)Instantiate(Resources.Load("gamePiece" + i), this.transform);
pieceInfo.currPos = 0;
pieceInfo.newPos = 0;
piecesList.Add(pieceInfo);
print(pieceInfo.gPiece);
}
}
it shows "gamePiece1" but I want it to have gamePiece0 and gamePiece1.
[1]: /storage/temp/172570-capture.png
Answer by CmdrZin · Dec 15, 2020 at 07:25 AM
Looks like you're just updating the .gPiece of your pieceInfo object. Try generating a new pieceInfo object each time or make the .gPiece an array and index it during the loop.
Answer by Llama_w_2Ls · Dec 15, 2020 at 07:36 AM
As CmdrZin said, you are just resetting the gPiece of the same class, instead of creating new ones. In the for loop, you need to have the line pieceList pieceInfo = new pieceList();
as well. @bellwether
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
List.Add just once in Update 2 Answers
[C#] Programm does not add to list 1 Answer
can add to a list but not remove 1 Answer