- Home /
Trying to understand parenting
Hi all, I'm still trying to wrap my head around parenting a game object. I have a player object with a nested game object ( gunContainer
)that has an animation I trigger on certain key inputs. When a user keys 1-4 on a keypad, in the Update method, I
instantiate the desired object
activeGun = Instantiate(guns[0], gunContainer.transform);
trigger the animation
when I first tried this, the new object was not at all where I expected it, so I changed a few things. Eventually, I fell on the following
...
if (Input.GetKey(KeyCode.Alpha1) || Input.GetKey(KeyCode.Keypad1))
{
if (activeGun == null)
{
activeGun = Instantiate(guns[0]);
}
}
...later in the update
if (activeGun != null)
{
activeGun.transform.SetPositionAndRotation(gunContainer.transform.position, gunContainer.transform.rotation);
}
This works but I do not understand why I have to explicitly reset the position and rotation on every frame. My mind thought I could just drop in the object and let the parent do its animation magic. Too easy?
Can someone explain to me why I have to match the parent transform and rotation every frame, where in my head I assumed as a child its transform and rotation would always be Vector3.zero / Quaternion.identity
Thanks!
Answer by Tkushn · Mar 07, 2019 at 07:22 PM
The instantiator is a child, but the object you instantiate is independant. So on it's prefab place a script and in OnStart or OnAwake put
Transform.SetParent(parent);
parent will have to be set to the object.
GameObject parent;
parent = GameObject Find(string name);
and then each instantiated object will have a parent
Your answer
Follow this Question
Related Questions
Positions to rotations of a regular GO 2 Answers
Following another object's position/rotation like parent/child relationship? 4 Answers
Best way to record/save race car runs 1 Answer
How to use the lerp function with rotation? (C#) 1 Answer
Changing object rotation in animation automatically changes it's position 1 Answer