I have 3 objects of Image
type in game scene. So I need to attach this 3 objects via script into Image
array inside of this script. How can I do this? I tried to use GetComponent
but they all have different names and actually I don't know how to attach them.
1 Answer
The first way is Using GameObject.Find(name)
which works fine as long as you know the name of objects but a more easy-to-manage way, which I prefer to use, is getting help from Unity's inspector: just make your array serializable and then just a simple drag and drop in the inspector! the only thing you need to do is add [Serializable]
before private
to tell the unity that "I want you to serialize this!" and then add game objects into the array in the inspector.
But of course, there are other ways, such as giving all of them the same tag (like UIImages
) and then finding them by GameObject.FindWithTag()
. But my advice is that if you know which objects you want in your array and it never changes then use the inspector's abilities, otherwise using tags is a good way to go.
Final note: you can group them all in the hierarchy (make them all children of an empty parent) and then find that one and use transform
to access its children
-
2\$\begingroup\$
Find(name)
should be avoided whenever possible. There are lots of better options for setting up references between objects. \$\endgroup\$– PhilippCommented Apr 16, 2022 at 15:33
private Image[] images;
? \$\endgroup\$