Home > Software engineering >  How to stop foreach loop which keeps adding the gameobjects
How to stop foreach loop which keeps adding the gameobjects

Time:12-18

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);
    }  
}

CodePudding user response:

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.

  • Related