Collision script doesnt work,OnCollisonEnter2D does not work if it collides with the enemy
public class EnemyHealth : MonoBehaviour
{
public float EnemyH = 20f;
public float damageAmount = 10f;
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Bullet")
{
EnemyH -= damageAmount;
}
}
private void Update()
{
EnemyDeath();
}
void EnemyDeath()
{
if(EnemyH < 1)
{
Destroy(gameObject);
}
}
}
I want to make a enemy health scipt that will destroy the enemy if the health reaches 0, does anybody know why it doesnt work ?, public class EnemyHealth : MonoBehaviour { public float EnemyH = 20f; public float damageAmount = 10f;
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Bullet")
{
EnemyH -= damageAmount;
}
}
private void Update()
{
EnemyDeath();
}
void EnemyDeath()
{
if(EnemyH < 1)
{
Destroy(gameObject);
}
}
}
I want to make a enemy health scipt that will destroy the enemy if the health reaches 0, does anybody know why it doesnt work ?
as well on both the bullet and the enemy on the collider is trigger has to be checked or it will not work
Answer by GDGames0302 · Jan 28, 2021 at 06:31 PM
Hi. You should have a rigidbody2d attached to the bullet, to the enemy or to both(at least to one of them). You should make sure that the bullets have "Bullet" tag. This script("EnemyHealth") should be attached to the enemy. If this still doesn't work, you should write a debug statement in OnCollisionEnter2D to see if the if-statement is executing. Also, you better use Destroy(this.gameObject) instead of Destroy(gameObject).
Answer by wolfgraphicsLLC · Jan 28, 2021 at 07:31 PM
the first thing i would say is can you provide some screen shots of the unity window not just the inspector or the scene view but whole window and this is what i need to see go to runtime ie hit play up top fire a bullet and the pause the runtime dont end it puase it the click on the enemy while clicked hold alt and type the prscr button and then in the chat input hold cntrl v will paste it in the chat is they allow images in them! then you would do the same while still pause click on the bullet and screen shot that and you could i guess email me the screen shots
Your answer
Follow this Question
Related Questions
Saving Data (please help) 0 Answers
"The associated script cannot be loaded." 0 Answers
Scripting Help desperately needed. 1 Answer
Update() and FixedUpdate() not running on C# scripts 0 Answers