I’m trying to populate a list of all GameObjects in my scene that have the “Pivot” tag and add them to a list.
The problem I’m having is that putting my code on Start only adds one object (not all) and putting it on Update adds the objects multiple times.
I want to use List.Contains to check that the item isn’t already in the list, but don’t know how to write it into my code, which I have posted below:
public List<GameObject> pivotList;
void Start()
{
pivotList = new List<GameObject>();
}
void Update()
{
pivotList.Add(GameObject.FindGameObjectWithTag("Pivot"));
}
}
Thanks in advance for help!
FindGameObjectWithTag() returns the first gameobject it finds with the tag. So in the update function you are indeed just adding the same object each frame. What you are looking for is FindGameObjectsWithTag() (notice the s after gameobject) , which returns an array of gameobjects instead of a single gameobject.
Then you turn the array in to a list and you are good to go. You could do this by just using a foreach loop, but there might be some array.ToList() function, but I’m not sure about that.
Tag your gameObject with a custom MonoBehaviour component, have it add itself to the list on Awake() or Start() or OnEnable(). Have it remove itself from the list on OnDestroy() or OnDisable() (mirror the adding behaviour)
I am not sure what are those tags meant for, but I’ve never used them in any project
Thanks, all!
@metalted had the answer that worked best. I was vastly overcomplicating things.
The array on Start was really all I needed to accomplish what I wanted to do, since the list of GameObjects is static.