I'm making a 2D platformer and I made an enemy that shoots the player when it is in a certain range, turns when player is on the other side and has an amount of health. But when I add a second enemy (I did this by duplicating) and try to kill that one first the first enemy gets killed and then I can kill the second enemy wich obviously is not what I want. The second one also only turns when the player is on the other side of the first enemy. That problem is probably the same mistake. I looked for multiple fixes but none of those have helped me so far. It would be great if someone could see the mistake I made. Here is EnemyShoot script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyShoot : MonoBehaviour
{
private Animator anim;
public GameObject snowBall;
public Transform throwPoint;
public AudioSource throwSound;
public float range;
private float distance;
private Transform player;
private Transform enemy;
private float timer;
public float timeBetweenShots;
// Use this for initialization
void Start()
{
timer = 0;
anim = GetComponent();
}
private void Awake()
{
enemy = GameObject.FindGameObjectWithTag("Enemy").transform;
player = GameObject.FindGameObjectWithTag("Player1").transform;
}
private void Update()
{
timer += Time.deltaTime;
if (enemy.position.x < player.position.x)
{
transform.localScale = new Vector3(1, 1, 1);
} else
{
transform.localScale = new Vector3(-1, 1, 1);
}
distance = Vector2.Distance(player.transform.position, enemy.transform.position);
if (distance < range && timer > timeBetweenShots)
{
GameObject ballClone = (GameObject)Instantiate(snowBall, throwPoint.position, throwPoint.rotation);
ballClone.transform.localScale = transform.localScale;
anim.SetTrigger("Throw");
throwSound.Play();
timer = 0;
}
}
}
And here is the EnemyHealth script (there is an enemyCounterin the gamemanager script):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealth : MonoBehaviour {
public int enemyLife;
public AudioSource hurtSound;
public void HurtEnemy()
{
enemyLife -= 1;
hurtSound.Play();
if (enemyLife == 0)
{
gameObject.SetActive(false);
FindObjectOfType().enemyCounter -= 1;
}
}
}
All help is much appreciated :)
↧