I created an enemy that gets hit by laserbeams or missiles. everything works fine, so I created a Prefab.
When I add to the Scene multiple Prefabs of the same Enemy, when one gets hit, all of them get damage at the same time like they are chained - how do I fix that?
but they don’t die at the same time, they wait for the last hit even if their health is 0…
is it because I use static variables for their health?(curLife, totalLife, percLife)
I have no experience in unity or c#, this is my first project trying to learn the code.
Thanks
This is the EnemyScript:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyScript : MonoBehaviour
{
private Laserbeam laserbeam;
private Missiles missile;
private static float totalLife = 20;
private static float curLife = totalLife;
public static float percLife = curLife / totalLife;
//Materials
private Material matWhite;
private Material matDefault;
private UnityEngine.Object explosionRef;
SpriteRenderer sr;
private void Awake()
{
laserbeam = GameObject.FindObjectOfType<Laserbeam>();
missile = GameObject.FindObjectOfType<Missiles>();
}
// Start is called before the first frame update
private void Start()
{
sr = GetComponent<SpriteRenderer>();
matWhite = Resources.Load("WhiteFlash", typeof(Material)) as Material;
matDefault = sr.material;
}
private void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("LaserBeam"))
{
Destroy(collision.gameObject);
curLife -= 1;
sr.material = matWhite;
explosionRef = Resources.Load("Explosion");
percLife = curLife/totaLife
if(curLife <= 0)
{
curLife = 0;
KillSelf();
}
else
{
Invoke("ResetMaterial", 0.05f);
}
}
if (collision.CompareTag("Missile"))
{
Destroy(collision.gameObject);
curLife -= 5;
sr.material = matWhite;
explosionRef = Resources.Load("Explosion");
percLife = curLife/totalLife
if (curLife <= 0)
{
curLife = 0;
KillSelf();
}
else
{
Invoke("ResetMaterial", 0.05f);
}
}
}
void ResetMaterial()
{
sr.material = matDefault;
}
private void KillSelf()
{
GameObject explosion = (GameObject)Instantiate(explosionRef);
explosion.transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
Destroy(gameObject);
}
}