how to break connection between gameobject and its clone in unity.
Hi, i have boxes gameobject and its children. Before i rotate or move this object, i insantiate all of them with using Record() method and if user want to take back action with using Undo() method, all objects including its clones is destroyed, so i dont want to destroy clone objects. how to break connection between gameobject and its clone. Sorry for my english thanks in advance. Here is the code
public Gameobject boxes, boxesCopy;
public void Record(){
if (boxesCopy != null) {
Destroy (boxesCopy);
}
boxesCopy=Instantiate(boxes);
boxesCopy.SetActive (false);
}
public void Undo(){
Transform[] realChildren = boxes.GetComponentsInChildren<Transform>();
foreach (Transform child in realChildren)
{
Destroy (child.gameObject);
}
Transform[] copyChildren = boxesCopy.GetComponentsInChildren<Transform>();
foreach (Transform child in copyChildren)
{
child.transform.parent = boxes.transform;
child.SetActive (true);
}
}
Answer by lacroix_math · Oct 30, 2018 at 02:13 PM
hi, there is probably numerous ways to do, but for me, it's simple. To attach an object, you do.
public bool if_Is_True;
Void Update() { if ( if_Is_True == true) { object_1.transform.parent = _player.transform // will attach object_1 to _player.. } else {
object_1.transform.SetParent(null); // will detach object_1 from _Player. }
So if you want to detach an object, juste add. object_1.transform.SetParent (null).
it work perfecly fine for me, to detaching trees from the base log, or Player to a Cart and moving both together.
Thanks, but i mean that i insantiate a gameobject which is existing already in my tree and if i destroy it and then its clone is also destroying or i change gameobject localscale and then clone's localscale is changing, there is a bound between them, i want to break its connection. I hope i could tell what my problem is
Sorry i found where i did mistake, GetComponentsInChildren finds children and its parent so i destroy parent too in old case and trying to attach it other children. i did like that and there is no problem. Thanks Transform[] realChildren = boxes.GetComponentsInChildren(); foreach (Transform child in realChildren) { if (child.gameObject.name != "boxes") { Destroy (child.gameObject); }
}