- Home /
specifying collider OnTriggerEnter
var health = 10; var points = 2;
function OnTriggerEnter (collision : Collider) { if (collision.gameObject.FindWithTag ("Player")) { var options = SendMessageOptions.DontRequireReceiver; collision.SendMessage("addHealth", health, options); collision.SendMessage("addPoints", points, options);
DestroyObject (gameObject);
Debug.Log("destoyed!");
}
else if(collision)
{
Destroy (GetComponent(Rigidbody));
}
}
this script is destroying my healthBox on impact with anything, how do i change this so that it is only affected when the player enters trigger?
it should be doing this anyway...
Answer by Statement · Jan 11, 2011 at 09:40 PM
Actually, you are looking for any object that has the tag player. What you want to do is compare tags, not find one with that tag.
See my revised code:
var health = 10; var points = 2;
function OnTriggerEnter (collision : Collider) { if (collision.CompareTag ("Player")) // Need to call CompareTag! { var options = SendMessageOptions.DontRequireReceiver; collision.SendMessage("addHealth", health, options); collision.SendMessage("addPoints", points, options);
DestroyObject (gameObject);
Debug.Log("destoyed!");
}
else if(collision)
{
Destroy (GetComponent(Rigidbody));
}
}
By the way, it appears as if there is a redudant test. if (collision) will always return true. I don't know why you want to remove the rigidbody upon impact though. Is this some sort of sticky object?
var health = 10; var points = 2;
function OnTriggerEnter (collision : Collider) { if (collision.CompareTag ("Player")) { var options = SendMessageOptions.DontRequireReceiver; collision.SendMessage("addHealth", health, options); collision.SendMessage("addPoints", points, options);
DestroyObject (gameObject);
Debug.Log("destoyed!");
}
// No need to have else if, the if always would return true anyway
else
{
// Are you really sure you want to remove the rigidbody?
// Just notifying you since it looks out of place.
// By the way, you don't need to call GetComponent with rigidbody.
Destroy (rigidbody);
}
}
it is a healthBox that drops from a dead enemy, so i want it to fall to the floor and then stick there untill the player walks into it.
thanx you have been a great help.
Your answer
Follow this Question
Related Questions
How can I detect if box is touching a tag named weapon? 1 Answer
How do I cause the collision of one object affect the movement of another object? 0 Answers
How to make player go through object but can't go back 3 Answers
Pick something up with name - ontrigger 1 Answer
How to Move Player in Particular Direction Without holding Down a Button? 0 Answers