Raiyan Chowdhury
Raiyan Chowdhury

Reputation: 311

Unity — How to set a GameObject to an Available Object through Script?

I'm a beginner in Unity development. I'm trying to set a GameObject using scripting, rather then via the inspector. Here's what I mean. Instead of setting the game object like this, by making Propeller public and setting it manually:

enter image description here

I want to set Propeller directly from my script. How can I do this?

Upvotes: 1

Views: 3601

Answers (1)

verified_tinker
verified_tinker

Reputation: 665

If the Game Object is a prefab...

...You can use Resources.Load("prefab path"). For this to work, you must create a Resources directory inside your Assets and put the prefab in there.

If it's a Game Object in the scene, you have several options.

All of these are slow and should only be called once, in Awake() or Start(), and cached in a member variable.

1) GameObject.Find()

You can enter the path to the Game Object in the hierarchy and get it that way.

However, you're hard-coding the path. The moment that, or the object's name, changes, you're going to have to change your code. Not ideal.

2) Transform.Find()

Unlike GameObject.Find(), this is not a static method. As such, you'll call it from the searching object's Transform: transform.Find().

I don't doubt this is a slow function as well, but it should be faster than the previous approach, as it only searches inside the object's children. It also suffers from the same "hard-coding" problem as GameObject.Find().

Keep in mind that it's not recursive; it won't search inside its children's children.

3) Component.GetComponent[s]InChildren()

Finally, if the Game Object you're searching for has a component specific to it, you can search for it with GetComponentInChildren<YourComponent>(). It will return the first occurrence of the component.

If you have several such children, you can make the "Component" part plural: GetComponentsInChildren<YourComponent>(). This will return an array containing every such component in the children.

You can then access their Game Objects by typing returnedComponent.gameObject.


However, I strongly recommend that you simply drag the object in the Inspector, unless you have a good reason not to. It's Unity's built-in way of dependency injection. Your scripts should not have to worry about getting data; only processing it.

Upvotes: 2

Related Questions