- Home /
Instantiate as children of GameObject hit by raycast.
I have made a script that instantiates a prefab at the location of a raycasthit. But how can i make it so this prefab also becomes a children of the gameobject it hits. So it will move with the gameobject.
My code looks like this do far:
var linePrefab : GameObject; var decalPrefab : GameObject;
function Shoot () { var rayDirection = SprayDirection(shotSpread);
if(Physics.Raycast(transform.position, rayDirection, hit, range)) {
if(hit.distance > minTrailDistance){
newLineObject = Instantiate(linePrefab);
newLine = newLineObject.GetComponent(LineRenderer);
newLine.SetPosition(0, transform.position);
newLine.SetPosition(1, hit.point);
}
Instantiate(decalPrefab, hit.point, Quaternion.LookRotation(hit.normal));//This instantiates the prefab i want to make a child of the raycasthit object.
hit.collider.gameObject.SendMessage("Damage", damage, SendMessageOptions.DontRequireReceiver);
if (hit.rigidbody){
hit.rigidbody.AddForceAtPosition(rayDirection * force,hit.point);
}
}
}
Answer by duck · May 20, 2010 at 09:48 AM
You need to capture the result returned by your Instantiate function in a variable. The result returned by a call to Instantiate is a reference to the newly instantiated item.
Once you've got this reference in a variable, you can then manipulate it using that variable as shown below:
//This instantiates the prefab i want to make a child of the raycasthit object: var decalInstance : GameObject = Instantiate(decalPrefab, hit.point, Quaternion.LookRotation(hit.normal));
//This parents the object to the object which was hit: decalInstance.transform.parent = hit.transform;
This is something that needs to be implemented in Version 3 of Unity. It should be possible to instantly "Instantiate as child" of the current transform, i.e. transform.Instantiate() should put the clone in local space and Instantiate() should be in world transform space. I think this functionality is at the core of what prefabs are about: i.e., not having to write a bunch of code for something that is intuitive.
I have added this to the Unity feedback page: http://feedback.unity3d.com/forums/15792-unity/suggestions/1418475-instantiate-as-child-function