- Home /
Parenting Instantiated objects on Collision
I'm looking for help on how to instantiate a gameobject at an exact location on a parent object. For instance, right now, after a collision, my Instantiated Object spawns as a child of the object I want it too, but at a different location everytime. Depending on where the collision happens, the new object can spawn more towards the head, the abdomen, or the feet of my target parent object.
My code is like this: public GameObject thing;
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Player")
thing = (GameObject)Instantiate (thing, transform.position + new Vector3(0f,0f,0f), Quaternion.identity);
thing.transform.parent = GameObject.FindGameObjectWithTag("Player").transform;
Destroy (gameObject);
Debug.LogError ("Hit gunpickup");
}
}
Answer by robertbu · Apr 12, 2014 at 05:06 AM
Insert at line 5 (after the parenting):
thing.transform.localPosition = Vector3.zero;
thing.transform.localRotation = Quaternion.identity; // May not be needed
Sorry I'm not sure why I edited your post and not added a new comment, I'm new to this Q/A community. I don't want to take your credit away.
I edited your answer and made made it a comment, but I'm unsure what you refer to. $$anonymous$$y original answer seems to be unchanged. Did the suggested line(s) of code work for you?
Answer by The Sauce · Apr 12, 2014 at 06:20 AM
Yes that works, thank you, very much appreciated. It does work without the extra Quaternion.identity.
Heres the full code for anyone else having trouble with this:
public GameObject thing;
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Player")
thing = (GameObject)Instantiate (thing, transform.position + new Vector3(5f,0f,0f), Quaternion.identity);
thing.transform.parent = GameObject.FindGameObjectWithTag("playercenter").transform;
thing.transform.localPosition = Vector3.zero;
//thing.transform.localRotation = Quaternion.identity; // May not be needed
Destroy (gameObject);
Debug.LogError ("Hit gunpickup");
}
}
The 'localRotation' line sets the rotations to match. Apparently you don't need this.
Your answer
Follow this Question
Related Questions
Parenting GameObjects 1 Answer
iOS Instantiate transform as child -- positioning bug 2 Answers
Howto set main.camera as a parent when main.camera itself is a child of a prefab 1 Answer
Getting transform from an instantiated clone to parent it? 1 Answer
how do i know where my instantiated object came from? 2 Answers