D
D
dashsk2021-03-13 09:59:07
C++ / C#
dashsk, 2021-03-13 09:59:07

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.
nZtNyJv.png
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}"));
        }
    }

I take it he can't find it.
NullReferenceException: Object reference not set to an instance of an object

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nivikantavo, 2021-03-13
@Nivikantavo

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

F
freeExec, 2021-03-13
@freeExec

Moreover, transformyou 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 question

Ask a Question

731 491 924 answers to any question