
In Unity 2020.3 LTS version, there are several ways to get a parent and child game object (GameObject) in Unity.
This section provides an example of how to use the "Transform.Find" function, and describes how to go back to the parent to retrieve another child object, as well as how to go back to the parent directory as a relative path, as in Linux and Windows file system.
You can use Transform.Find
to get the child object.
When the script attached to Enemy GameObject in hierarchy as shown below, you can get Wolf's Transform using this.gameObject.transform.Find("Monster/Wolf")
.
The sample code is here.
public class EnemyBehaviour : MonoBehaviour{
void Start() {
GameObject wolf = this.gameObject.transform.Find("Monster/Wolf").gameObject;
}
}
If you have the following structure, first get the parent object "Enemy", and then use
transform.Find("Monster/Wolf")
to get Wolf, using the parent object as a base point.
The sample code is here.
public class EnemyBehaviour : MonoBehaviour{
void Start() {
Transform enemyTransform = this.gameObject.transform.parent;
this.wolf = enemyTransform.Find("Monster/Wolf").gameObject;
}
}
This can also be written as a path in one shot with Transform.
public class EnemyBehaviour : MonoBehaviour{
void Start() {
this.wolf = this.gameObject.transform.Find("../Monster/Wolf").gameObject;
}
}
This was a memo on how to use Transform. Thanks for reading!
date | modification |
---|---|
none |
Thank you for your message.
Sorry. The Error has occurred.We apologize for the inconvenience.Please try again in a few minutes or contact us via DM below.
Twitter:@NodachiSoft_engName:Send the following information to us. If you are happy with your submission, please click "Send". If you want to modify it, please click "Back".
Name: