I am using instantiate() to clone a gameobject and have stored the cloned gameobject in a variable named rocketInstance.This new gameObject have three children named marker,starter and plane. I want to store the marker gameObject in a variable named trrigerObject. I have tried the following
trrigerObject=rocketInstance.marker;
trrigerObject=rocketInstance.GetComponent(“marker”);`
Easiest way would be : Get Child transform using its index , and then get GameObject of that child transform:
GameObject ChildGameObject1 = ParentGameObject.transform.GetChild (0).gameObject;
GameObject ChildGameObject2 = ParentGameObject.transform.GetChild (1).gameObject;
And so on …
I would attach a script to your marker gameobject like so:
// C#
public GameObject myMarker;
void Start()
{
marker = this.gameObject;
}
// JS
var myMarker : GameObject;
function Start()
{
marker = this.gameObject;
}
Making it public means other scripts can now access this gameobject.
just use this.trrigerObject must be GameObject variable
trrigerObject=rocketInstance.GetChild("marker");
for heaven sake, there is not any get sub child by name or by tag, what if I have many sub children
I have this little extension that isn’t efficient at all, but does do what you’re expecting.
using UnityEngine;
using System.Collections;
public static class ExtensionMethods {
public static GameObject FindChildByName(this GameObject target, string name) {
if (target.name == name) return target;
for (int i = 0; i < target.transform.childCount; ++i) {
var result = FindChildByName(target.transform.GetChild(i).gameObject, name);
if (result != null) return result;
}
return null;
}
}
You would use it like:
using UnityEngine;
using System.Collections;
public class ExampleScript : MonoBehaviour {
private GameObject parentObject; // set in inspector
void Update() {
GameObject childObject = parentObject.FindChildByName("ChildGameObjectName");
if (childObject != null) {
Debug.Log("Found Child:" + childObject.name);
}
}
}
Maybe this will help someone in the future?