- Home /
OnCollisionEnter Destroy gameObject and Instantiate only 1 prefab?
I have a problem here whit this script.
I have put this script on a Cube with a Rigidbody and when the Cube falls down on the floor it destroys itselfe like I wrote in the script but it spawns 4 prefabs because the cube collides with the 4 edges on the floor in one frame.
I tryed to write a var with prefabiscreated into the OnCollisionEnter function to hopefully prevent more spawning of the prefabs but it does not work.
#pragma strict
private var propInfo : Prop_Info;
function Awake()
{
propInfo = GetComponent(Prop_Info);
}
function OnCollisionEnter (collision : Collision)
{
var prefabiscreated : boolean = false;
if(propInfo.PropBreakSettings.canbreak == false)
return;
else if (!prefabiscreated)
{
if (collision.relativeVelocity.magnitude > propInfo.PropBreakSettings.breakForce)
{
prefabiscreated = true;
Instantiate (propInfo.PropBreakSettings.brokenObject,transform.position, transform.rotation);
Destroy(gameObject);
}
}
}
Answer by Harry64 · Aug 04, 2013 at 10:30 PM
I solved the problem very easy... stupid me. ^^;
private var propInfo : Prop_Info;
private var destroyMe : boolean = false;
function Awake()
{
propInfo = GetComponent(Prop_Info);
}
function Update()
{
if (destroyMe == true)
{
Instantiate (propInfo.PropBreakSettings.brokenObject,transform.position, transform.rotation);
Destroy(this.gameObject);
}
}
function OnCollisionEnter (collision : Collision)
{
if(propInfo.PropBreakSettings.canBreak == false)
return;
if (collision.relativeVelocity.magnitude > propInfo.PropBreakSettings.breakForce)
{
destroyMe = true;
}
}
Answer by gregzo · Aug 04, 2013 at 09:25 PM
Hi,
The only way 4 prefabs would be instantiated with this code is if OnCollisionEnter is called 4 times.
Your prefabiscreated bool is useless, because it is declared in the function and will always be false, whenever OnCollisionEnter is called.
The problem is somewhere else, not in this script. By the way you should simplify your OnCollisionEnter method by removing prefabiscreated completely :
function OnCollisionEnter (collision : Collision)
{
if(propInfo.PropBreakSettings.canbreak == false)
return;
if (collision.relativeVelocity.magnitude > propInfo.PropBreakSettings.breakForce)
{
Instantiate ( propInfo.PropBreakSettings.brokenObject, transform.position, transform.rotation );
Destroy(this.gameObject);
}
}
I wrote above that the cube is hitting the floor with his flat side. so all 4 edges hit the floor at the same time so the oncollisionenter is also called 4 times in one frame (if I rotate the cube a little bit then it creates sometimes only 2 or 3 prefabs). and that is my problem. how to I tell the script that it should just instantiate this prefab 1 time.