- Home /
How to destroy a gameobject when I collide with it?
I know how to destroy a game object but I want the object to be destroyed when my player which is a lawn mower collides with the grass. The mower name is "LawnMower" and the grass is named "grass_clump_04". If somebody could please help me with this aswell as how do I make the game go to the ending screen after I destroyed all the grass objects. Thanks in advance.
Answer by meat5000 · Aug 19, 2013 at 06:27 PM
Something like this attached to the object you want to destroy?
function OnCollisionEnter(col : Collision)
{
if(col.collider.gameObject.name == "LawnMower")
{
Destroy(gameObject);
}
else if (col.collider.gameObject.name != "LawnMower")
{
//Something else
}
}
End level, something like this attached to the Player:
var grassObjects : GameObject[];
function Update()
{
grassObjects = FindGameObjectsWithTag ("Grass");
var count = grassObjects.length;
if ( grassObjects == 0 )
{
//End level by showing end screen or loading next etc
//Debug.Log("No Grass Left");
//Application.LoadLevel ("NextLevel");
}
}
Make sure you tag your grass as "Grass" in the inspector. Add a tag by increasing the Elements by one and adding it in the new empty field.
You probably will want to do this periodically rather than every frame to avoid chewing up your cpu cycles. Find functions are very expensive. Try looking in to this:
Its all untested, I could be wrong. Let me know if it throws up errors :)
I tried the end level but it didnt work which I'm sure is my error. I'm new to scripting so I dont really know how any of this works or what to apply things to.
Answer by kyogretcg · Aug 19, 2013 at 06:34 PM
The grass gets destroyed but I havent tested the end level.
I think you were trying to post a comment to meat5000s answer. Slow down. Read the buttons.
Your answer
Follow this Question
Related Questions
When i run Unity3D leaves a freak message 1 Answer
Variable problem in Javascript. 3 Answers
how can i make a ball bounce when i click on it 1 Answer
How to add play again or quit dialog 1 Answer
How do i make realistic fish jump? 1 Answer