- Home /
Problems With Damaging Enemies on Trigger
Hi all, I'm having a lot of trouble trying to understand why i cant get my value for damage to when switching projectiles. I currently have 4 scripts that are called on a collision with a player projectile. Firstly, Collision Handling checks to see if the collision is a player projectile and subsequently gets the damage value associated with it from the projectiles script. Then it subtracts the damage value from the value for health in the Enemy Handling script. This is then checked in the next script (in this case "Grunt") to see if the value of EnemyHandling.health is less than or equal to zero, at which case the object will be deleted. The problem is, even with all of my projectiles having differing damages, the enemies are instantly deleted upon the trigger. It should be noted that none of the projectiles have a damage equal to or above the value for health. Any and all help will be greatly appreciated. Associated code below:
public class CollisionHandleling : MonoBehaviour {
public float damage;
public GameObject fireBallExplosion;
public EnemyHandling enemy;
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Player Projectile")
{
if (col.gameObject.name == "fireBall")
{
Instantiate(fireBallExplosion, col.transform.position, col.transform.rotation);
// Getter
damage = col.gameObject.GetComponent<fireBall>().damage;
}
else if (col.gameObject.name == "axeMagic")
{
// Getter
damage = col.gameObject.GetComponent<axeMagic>().damage;
}
else if (col.gameObject.name == "iceMagic")
{
Instantiate(fireBallExplosion, col.transform.position, col.transform.rotation);
// Getter
damage = col.gameObject.GetComponent<iceMagic>().damage;
//Slow
enemy.speed /= 2;
}
// Destroy projectile
Destroy(col.gameObject);
// Setter
enemy.health -= damage;
}
}
}
public class EnemyHandling : MonoBehaviour { public float health = 100f; public float speed = 1f;
}
public class Grunt : MonoBehaviour {
private float speed;
private Rigidbody2D rb;
private Vector2 Matrix;
public EnemyHandling enemy;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
enemy = GetComponent<EnemyHandling>();
}
// Update is called once per frame
void Update () {
speed = enemy.speed;
Matrix =new Vector2(speed, 0);
// killing enemy
// get health
if (enemy.health <= 0f)
{
Destroy(gameObject);
}
}
void FixedUpdate()
{
rb.MovePosition(rb.position - Matrix * Time.deltaTime);
}
}
I didn't notice any glaring issued with the code. Is it possible that the CollisionHandling script is on the wrong game object and you are destroying the enemy ins$$anonymous$$d of the projectile?
Your answer
Follow this Question
Related Questions
Adding jump animation in script editor [2D Project] 0 Answers
Save score across scenes 1 Answer
Sprite Renderer Not Changing Sprite via Script 1 Answer
Moving parent from child' script doesn't work 0 Answers
Question on 2d planet gravity 1 Answer