- Home /
How to detach only one child from a parent through script (C#)
I have a gameobject that is a parent of a weapon and body parts I want to detach the weapon gameobject only, and make the body parts stay as a child of the parent gameobject. I would have tried
using UnityEngine;
using System.Collections;
public class P1WeaponGrabbing : MonoBehaviour {
public Transform Character;
if(Boolean == false) {
Character.DetachChildren();
}
}
But it will detach all children in the parent.
Thanks in advance
Answer by AidanHockey5 · Apr 17, 2016 at 11:49 AM
Get a reference to the Transform of the object you want to detach from it's parent. Then, set that transform's parent to null.
public Transform myChildObject;
public bool detachChild;
void Update ()
{
if(detachChild == true)
{
myChildObject.parent = null;
}
}
Thanks for this tip! It worked just fine for me.
The objective was the same: detach the weapon from the dead npc's hand.
Apparently SetParent(null) is recommended, because it provides the optional worldPositionStays parameter.
Answer by Cherno · Apr 16, 2016 at 04:56 PM
Use transform.parent = parentTransform or transform.SetParent to set parent transforms individually. Use transform.parent = null for no parent.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity 4.6: How to swap childs (without detaching them)? 1 Answer
How to get a certain child from a Canvas? 1 Answer
Making child components interactive c#? 0 Answers