0
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ inside of which script exactly? I can't see any code on your question. \$\endgroup\$
    – Arian_ki
    Commented Apr 16, 2022 at 13:16
  • \$\begingroup\$ @Arian_ki Is is better for you if I write private Image[] images;? \$\endgroup\$
    – Silz
    Commented Apr 16, 2022 at 13:21

1 Answer 1

0
\$\begingroup\$

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

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Find(name) should be avoided whenever possible. There are lots of better options for setting up references between objects. \$\endgroup\$
    – Philipp
    Commented Apr 16, 2022 at 15:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .