- Home /
How to get access to child's objects of instantiated prefab on JS?
Have created in "Resources" folder "Body.prefab" and "Obj.prefab". Body.Prefab Hirerarchy is
"Body" (GO with mesh)
|_"1st-Dummy" (GO without mesh)
|_"2nd-Dummy" (GO without mesh)
|_"3rd-Dummy" (GO without mesh)
|_"4th-Dummy" (GO without mesh)
need to get after instantiating
"Body" (GO with mesh)
|_Objects (Empty GO)
| |_first
| |_second
| |_third
| |_fourth
|
|_"1st-Dummy" (GO without mesh)
|_"2nd-Dummy" (GO without mesh)
|_"3rd-Dummy" (GO without mesh)
|_"4th-Dummy" (GO without mesh)
use JavaScript to instantiate Body prefab
var Body : GameObject;
var first : GameObject;
var second : GameObject;
var third : GameObject;
var fourth : GameObject;
function Start () {
Body = Instantiate(Resources.Load("Body.prefab", GameObject));
Body.Transform.Position = Vector3.Zero;
Body.Transform.Rotation = Quaternion.identity;
first = Instantiate(Resources.Load("Obj.prefab", GameObject));
}
Can I load prefab and give it another name that propose me unity3d? (It calls "Body(clone)", I want to call it "Body")
How Can I set transform position of first variable to child postion of 1st-Dummy of Body instantiated prefab.
How can I to put first variable to be child of Body?
Answer by StephanK · Jan 27, 2013 at 01:27 PM
loadedPrefab.name = "Body";
first.transform.position = Body.FindChild("1st-Dummy").position; (Although it would be better to have a direct reference to your dummies.)
first.transform.parent = Body.transform;
Answer by LINKeRxUA · Jan 28, 2013 at 11:43 AM
first.transform.position = Body.FindChild("1st-Dummy").position; (Although it would be better to have a direct reference to your dummies.) Doesn't work. Show's me error that can fing in UnityEngine "FindChild"
first.transform.position = Body.transform.Find("1st-Dummy").position;
Answer by moeid · Dec 08, 2013 at 09:46 AM
hi. i think this is the best way to access to the child of a prefab that instantiated.
using UnityEngine; using System.Collections;
public class CreatNewPlanet : MonoBehaviour { public Transform myprefab;
private Transform NewGameObject;
TextMesh xmesh=new TextMesh();
// Use this for initialization
void Start () {
}
bool clicked=false;
// Update is called once per frame
void Update ()
{
if(!clicked)
{
if(Input.GetKey(KeyCode.T))
{
NewGameObject=Instantiate(myprefab,new Vector3(12,-3,0),Quaternion.identity) as Transform;
clicked=true;
print(NewGameObject.GetChild(4).name);
xmesh=NewGameObject.GetChild(4).GetComponent(typeof(TextMesh)) as TextMesh;
xmesh.color=Color.blue;
xmesh.text="------X:"+ ((int)(NewGameObject.GetChild(3).transform.position.x)) .ToString ();
}
}
}
}