I successfully set up a script that duplicates my enemy from a prefab that I created. The original enemy can approach me and deal damage, but the rest of the enemies cannot! I don’t know why they can’t deal any damage and I would like to fix it.
Here is the script that spawns them:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnEnemy : MonoBehaviour
{
public GameObject enemytospawn;
public Transform spawnplace;
public int timebetweenspawn;
public int enemiesperround;
IEnumerator task()
{
for (int i = 0; i < enemiesperround; i++)
{
Instantiate(enemytospawn, spawnplace.position, spawnplace.rotation);
yield return new WaitForSeconds(timebetweenspawn);
}
}
void Awake ()
{
StartCoroutine(task());
}
}
And here is the enemy script itself:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class EnemyAI : MonoBehaviour
{
public Transform target;
public float moveSpeed;
public int rotationSpeed;
public float maxdistance = 0.3f;
private int attackcooldown;
public Slider HealthSlider;
public int enemydamage = 3;
public int enemyhealth;
public UnityStandardAssets.Characters.FirstPerson.FirstPersonController Controller;
private Transform myTransform;
//If the enemy dies...
void enemydeath ()
{
Destroy(gameObject);
}
void Awake()
{
myTransform = transform;
attackcooldown = 0;
}
void Start()
{
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
maxdistance = 1.3f;
}
IEnumerator Wait()
{
yield return new WaitForSeconds(0.4f);
attackcooldown = 0;
}
void Update()
{
Debug.DrawLine(target.position, myTransform.position, Color.red);
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
if (Vector3.Distance(target.position, myTransform.position) > maxdistance)
{
//Move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
if (Vector3.Distance(target.position, myTransform.position) < maxdistance && attackcooldown == 0)
{
attackcooldown = 1;
Debug.Log("enemy hit you!");
Controller.GetComponent<PlayerVitals>().healthSlider.value = Controller.GetComponent<PlayerVitals>().healthSlider.value - enemydamage;
StartCoroutine (Wait());
}
if (enemyhealth <= 0)
{
enemydeath();
}
}
}
It is also worth mentioning that I cannot get line 67 of the above code to work. No matter what I try it just says
NullReferenceException: object reference not set to an instance of an object
Please help