- Home /
If Check Colliding GameObject Variable
I'm looking for a way to check a variable in the script of a gameObject my player is colliding with. Here is what I currently have:
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Enemy")
{
hitPoints = hitPoints - 1;
}
}
What I want is for "hitPoints = hitPoints - 1;" to fire only if the colliding gameObject has the tag "Enemy" and if that specific Enemy instance's own hit points variable is above zero. How would I do that?
Answer by OncaLupe · Nov 01, 2015 at 11:28 PM
You need to get a reference to the other object's script using GetComponent, then you can access the variable provided it's public.
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Enemy")
{
EnemyScript enemy = collision.gameObject.GetComponent<EnemyScript>();
if(enemy != null && enemy.hitPoints > 0)
{
hitPoints -= 1;
}
}
}
Replace 'EnemyScript' with whatever you call your enemy's script.
Your answer
Follow this Question
Related Questions
unity2D colliders not working properly,,Unity2D Colliders don't seem to be working HELP PLEASE! 0 Answers
How to stop object from going through walls. 4 Answers
Create A Counter And GameObjects Unique ID 1 Answer
How can I check if an instantiated object collides with another instantiated object? 1 Answer