2

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?

1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The final comment is the important part here! The reason Unity works this way is because it manages what is loaded with your scene, rather than having everything loaded at game start, and keeps this updated as you work on the project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.