- Home /
Instantiate as child
I'm trying to make it so that when a collision happens, an object is instantiated at an exact point as the child of another object. How can I do this?
Please add next time more details because your question is very abstract: when "a collision" happens; child "of another" object. And since you didn't post any code you have so far, we only can guess what language you use / want use.
Answer by Bunny83 · Jan 25, 2011 at 07:16 PM
I guess you use JS (because most beginners use JS ;) but i prefer C#)
One way would be something like:
var yourPrefab : Transform; var anotherObject : Transform;
function OnCollisionEnter (collision : Collision){ var anObject : Transform; anObject = Instantiate(yourPrefab, Vector3.zero, Quaternion.identity); anObject.parent = anotherObject; anObject.localRotation = Quaternion.identity; // rotates the object like the parent anObject.localPosition = Vector3(XX,YY,ZZ); // define here your "exact point" within the parent }
You have to give more information whether you want a exact local or global position and if one of your "objects" is involved in the collision?
Answer by Jessy · Jan 25, 2011 at 07:04 PM
You instantiate first, then you parent. You can always set position, and after the parenting, set localPosition if you want, instead.
Answer by Ziron999 · Mar 08, 2014 at 05:35 AM
in c# it had to be done like this. Adding this info for anyone else searching for this solution.
GameObject player;
GameObject playerClone;
void Start () {
player = Resources.Load("Player") as GameObject;
Instantiate(player);
playerClone = GameObject.Find("Player(Clone)");
playerClone.transform.parent = GameObject.Find("Main Camera").transform;
}
You should avoid using GameObject.Find() where possible as it will be relatively slow. In this case you can simply cast the newly created player object:
GameObject player;
GameObject playerClone;
void Start () {
player = Resources.Load("Player") as GameObject;
playerClone = Instantiate(player) as GameObject;
playerClone.transform.parent = GameObject.Find("$$anonymous$$ain Camera").transform;
}
Note that if you only want to parent to the current game object (which the script is attached to) you can just use playerClone.transform.parent = transform. Which will save you another GameObject.Find()