I have an enemy object with scripts and components and a figure. I clone this object when the game starts. I have an empty spawner game object that creates these clones and a raycast from my gun object that decreases their health. For some reason, no matter which clone I hit, it only decreases the health of the last clone created. Also, even when the last clones health drops below zero, it doesn't destroy itself as my code says it should.
The code for the spawner:
public class Spawner : MonoBehaviour
{
public GameObject prefab;
public GameObject clone;
public int maxEnemies = 10;
public int enemies = 0;
void Update()
{
if(enemies < maxEnemies){
clone = (GameObject)Instantiate(prefab, transform.position, Quaternion.identity);
enemies += 1;
}
}
}
The code for the enemy:
public class Mutant : MonoBehaviour
{
public Character player;
public Transform enemyTransfrom;
public Spawner spawner;
public float speed = 10f;
public float maxDis = 0.5f;
public float minDis = 1.5f;
public float health = 10;
public bool dying = false;
void Update()
{
if(health > 0){
transform.LookAt(player.transform);
if(Vector3.Distance(enemyTransfrom.position, player.transform.position) > minDis){
enemyTransfrom.position += enemyTransfrom.forward * speed * Time.deltaTime;
speed = 30f;
if(Vector3.Distance(enemyTransfrom.position, player.transform.position) <= maxDis){
speed = 10f;
fighting = true;
}else{
fighting = false;
}
}
}else{
dying = true;
speed = 0f;
fighting = false;
}
}
public void Die(){
Object.Destroy(spawner.clone);
spawner.enemies -= 1;
}
When dying is true, it starts an animation that runs the function die() at the end of it.
Finally, the code for the raycast:
private Vector3 direction;
public Transform shootPoint;
public Transform blaster;
public Transform shotTarget;
void Update()
{
direction = shotTarget.position-transform.position;
Debug.DrawRay(shootPoint.position, direction, Color.red);
RaycastHit hit;
Ray beam = new Ray(blaster.position, direction);
if(Physics.Raycast(beam, out hit, 1000)){
if(hit.collider.tag == "Enemy"){
enemy.health -= 10;
}
}
I've been struggling with this for a while and any help would be greatly appreciated. Thanks!
↧