I made an enemy that follows me and I wanted to spawn multiple instances of it in a round-like fashion. I made it into a prefab and made a script that duplicates the prefab. My problem is that the “prefab” enemies (the duplicates) don’t deal damage to the player.
I also noticed that I cannot set the values of the prefab in the inspector tab.
Here is the script that controls my enemy. It is very messy but it works.
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 int PlayerPoints;
private Transform myTransform;
//If the enemy dies...
void enemydeath ()
{
Destroy(gameObject);
GetComponent<PointManager>().points = GetComponent<PointManager>().points + 50;
PlayerPoints = GetComponent<PointManager>().points;
GetComponent<PointManager>().ScoreText.text = "" + PlayerPoints;
}
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();
}
}
}
also, I get a “Object reference not set to an instance of an object” error on line 72 if anyone knows how to fix that.
