Hey guys I wrote an AI script that was supposed to make the enemy rotate towards the player once he enters it’s trigger collider but everytime I run it unity freezes. Here’s the code:
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public float speed = 2.0f;
public GameObject target;
public float dist;
// Use this for initialization
void Start () {
GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update () {
dist = Vector3.Distance(transform.position, target.transform.position);
}
void OnTriggerEnter(Collider hit){
while(hit.gameObject.tag == "Player"){
transform.rotation = Quaternion.Lerp(transform.rotation, target.transform.rotation, Time.deltaTime * speed);
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
}
}
PS: I tried “if” instead of “while” but in only worked on rotating the enemy one frame
In Start(), you should probably recode to “target = GameObject.FindGameObjectWithTag(“Player”);” or remove your start function altogether. You are probably getting a null reference exception because target is null.
You could modify your loop to something like this and probably wou’ll get what you want:
void onTriggerEnter(Collider hit)
{
while (true)
{
/* your code here */
/* here you create some collision verification, like OverlapSphere, and if it doesn't collide, you just break and leave the loop */
}
}