Answer the question
In order to leave comments, you need to log in
How to add to List GameObject through for loop?
Hello everyone, in Unity very recently, I ran into a problem. The script itself hangs on the CanvasManager. You need to find all Screen (this is a gameobject with canvas components) and push it into List _canvas.
I wrote this code but it doesn't work
private List<GameObject> _canvas;
void Start()
{
for (int i = 1; i <= 4; i++) {
_canvas.Add(GameObject.Find($"Screen{i}"));
}
}
Answer the question
In order to leave comments, you need to log in
Searching through names is not very correct, you can try using the GameObject.FindGameObjectsWithTag tags - https://docs.unity3d.com/ScriptReference/GameObjec...
or, if a script hangs on these objects, use FindObjectOfType as the best option, https:// docs.unity3d.com/ScriptReference/Object.Fi...
In general, you can pre-assign in the inspector, which is much easier
Moreover, transform
you can query its child objects. This is definitely better than looking for objects in the whole scene.
But in your case, where, all the elements of the canvas are ideal GetComponentsInChildren<Canvas>()
, unless of course they are not deeper there.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question