I am a beginner to scripting and I am having trouble with my enemy AI script, there are a few things I want to fix on it which are… after my player dies the enemy keeps trying to target the destroyed player’s transform. That one should be a simple fix to the code, I just don’t exactly know how to go about fixing it. Afterwards… a new problem arises, when the player is respawned, the enemy will not target the player.
Here is the script I am using:
using UnityEngine;
using System.Collections;
public class EnemyIntelligence : MonoBehaviour{
public Transform target;
public float moveSpeed;
private Transform myTransform;
private bool moving;
private bool targetting;
private Animator animator;
private bool idle;
EnemyHealth enemyhealth;
void Awake ()
{
myTransform = transform;
}
// Use this for initialization
void Start ()
{
animator = GetComponent<Animator> ();
enemyhealth = GetComponent<EnemyHealth> ();
GameObject go = GameObject.FindGameObjectWithTag ("Player");
target = go.transform;
if (moving) {
moving = false;
animator.SetBool ("Moving", false);
}
if (moveSpeed > 0) {
moving = true;
animator.SetBool ("Moving", true);
}
if (enemyhealth.hurt == true) {
moveSpeed = 0;
}
}
// Update is called once per frame
void FixedUpdate (){
Debug.DrawLine (target.position, myTransform.position, Color.red);
float dist = Vector2.Distance(target.position, transform.position);
if (dist < 5) {
moveSpeed = 1;
}
if (dist > 5) {
moveSpeed = 0;
}
if (target.position.x < myTransform.position.x)
myTransform.position -= myTransform.right * moveSpeed * Time.deltaTime; // player is left of enemy, move left
else if (target.position.x > myTransform.position.x)
myTransform.position -= myTransform.right * moveSpeed * Time.deltaTime; // player is right of enemy, move right
//Enemy face target
if (target.position.x < myTransform.position.x)
transform.eulerAngles = (moveSpeed>0)?Vector2.up * 1:Vector2.zero;
if (target.position.x > myTransform.position.x)
transform.eulerAngles = (moveSpeed>0)?Vector2.up * 180:Vector2.zero;
}
}