- Home /
Projectile selectively passing through enemies
Greetings,
I am having problems fixing a bug with my isometric 2d action game.
The fireball projectile I have created will hit and kill an enemy, but when there are multiple enemies present, it seems to select only one enemy that it will hit and passes through all other enemies.
When the "selected" enemy dies, it will select a different enemy and pass through all others.
How do I fix this?
The script I am using for the fireball can be found below:
public class FireballController : MonoBehaviour {
//reference variables for use with damage, collision, and position
GameObject enemy;
EnemyHealth enemyHealth;
Animator anim;
private Rigidbody2D rb2d;
public int attackDamage = 100; //Damage per fireball hit
public float speed = 30; //initial force added to fireball projectile
void Start ()
{
//setup reference variables for damage, collision, and position
rb2d = GetComponent<Rigidbody2D>();
rb2d.AddForce(transform.up * speed); //adds initial force to fireball when spawned
Destroy(gameObject, 5);
anim = GetComponent<Animator>();
}
void OnTriggerEnter2D(Collider2D other)
{
// If the entering collider is the enemy...
if (other.gameObject == GameObject.FindGameObjectWithTag("Enemy"))
{
enemy = GameObject.FindGameObjectWithTag("Enemy");
enemyHealth = enemy.GetComponent<EnemyHealth>();
// ... damage the enemy.
enemyHealth.TakeDamage(attackDamage);
rb2d.velocity = new Vector2(0, 0);
anim.SetBool("explode", true);
Destroy(gameObject);
}
}
}
Please note that this is my first game in Unity and my first time posting on the forums. I am aware that I have no idea what I'm doing, so helpful comments only please :)
Answer by Vega4Life · Dec 04, 2018 at 06:03 PM
It seems to be this:
if (other.gameObject == GameObject.FindGameObjectWithTag("Enemy"))
This will find the same enemy every time. Instead, maybe just do this:
if (other.gameObject.tag == "Enemy"))
Then you should get what you want.
Answer by seeker727 · Dec 05, 2018 at 02:23 AM
Thank you for your assistance!
Initially, this solved the problem of the projectile passing through enemies, but it then caused the projectile to sometimes affect a different enemy than the one it collided with.
I then also changed
enemy = GameObject.FindGameObjectWithTag("Enemy");
to
enemy = other.gameObject;
And the bug is completely fixed!
Thank you for your assistance and for teaching me something today :)
Your answer
Follow this Question
Related Questions
Asset store Crash how do I fix ? 1 Answer
How do i fix this? 0 Answers
[Solved] Bug with disabling Polygon Collider 2D 0 Answers
Bugs in a pick up script 1 Answer