- Home /
Replace a child gameobject by an other at runtime
I want to replace a child gameobject by an another one at the same level of hierachy.
I tried to copy the transform.parent value of the original object before instanciate a new one and copy the transform on it then destroy the primary child object. But it doesnt work. The instanciate object is not instanciate as a child and i got a MissingReferenceExeption because i try to access a destroyed object.
here is my code :
using UnityEngine;
using System.Collections;
public class EditorManager : MonoBehaviour {
void StartPlaceObjs () {
GameObject mybutton;
GameObject myref;
myref=GameObject.Find("Button_Objects");
mybutton=EditorData.editorPrefabs[7];
mybutton.transform.parent = myref.transform.parent;
GameObject.Instantiate(mybutton);
GameObject.DestroyImmediate(myref);
}
}
Answer by aldonaletto · Aug 17, 2012 at 03:04 AM
You're trying to set the prefab's parent! Get a reference to the newly created object, then set its parent:
... void StartPlaceObjs () { GameObject mybutton; GameObject myref;
myref=GameObject.Find("Button_Objects");
mybutton=EditorData.editorPrefabs[7];
// get a reference to the instantiated object:
GameObject newObj = GameObject.Instantiate(mybutton) as GameObject;
// copy parent (maybe you should copy the position and rotation as well)
newObj.transform.parent = myref.transform.parent;
GameObject.DestroyImmediate(myref);
} }
Thanks a bunch you were right I had to create a reference to a new object first and copy position and rotation as well. I set the name also for future reference. The GameObject.DestroyImmediate had to be replaced by GameObject.Destroy to remove the error message. The script is working perfectly now thanks to you.
void StartPlaceObjs () {
GameObject mybutton;
GameObject myref;
myref=GameObject.Find("Button_Objects");
mybutton=EditorData.editorPrefabs[7];
// get a reference to the instantiated object:
GameObject newObj = GameObject.Instantiate(mybutton) as GameObject;
// copy parent,pos,rot and set name
newObj.transform.parent = myref.transform.parent;
newObj.transform.rotation = myref.transform.rotation;
newObj.transform.position = myref.transform.position;
newObj.transform.name="Button_Objects_Down";
GameObject.Destroy(myref);
}
Your answer
Follow this Question
Related Questions
Replace gameobject with another 0 Answers
Replace GameObject with another GameObject 2 Answers
Change the mesh of a gameObject 1 Answer
SOLVED - String replace % with " in C# 1 Answer
Replace GameObject with different FBX 0 Answers