Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop foreach loop which keeps adding the gameobjects

In unity 3d I have 2 gameobjects tagged as Character. I just wanted to add these two gameobjects into a List named characterList. I tried to do that with a foreach loop as shown in the below code. But then this loop keeps going on endlessly adding these two gameobjects over and over again. How can I make it stop after adding these 2 or anymore gameobjects that are actually in the scene?

private GameObject character;

public List<GameObject> characterList = new List<GameObject>();


void Start()
{
    foreach(GameObject character in GameObject.FindGameObjectsWithTag("Character"))
    {
        characterList.Add(character);
    }  
}
like image 498
prkash Avatar asked May 13 '26 11:05

prkash


1 Answers

OP:

But then this loop keeps going on endlessly adding these two gameobjects over and over again.

You have declared characterList as a public field and so it is subject to Unity serialisation:

public List<GameObject> characterList = new List<GameObject>();

I suspect what is happening is that when you:

  • run the game (or whilst editing if your script is marked as [InitializeOnLoad]) and the code adds to the collection

  • you make changes directly from the Editor

...Unity will persist the changes for the next run, resulting in the 2 added from the prior run plus 2 more for the current execution. This will increase logarithmically per run.

An easy fix is to define your field as private like so:

private List<GameObject> characterList = new List<GameObject>();

Unity will then ignore it and won't attempt to serialise it nor will it show the member in the Editor thus avoiding accidental adds.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!