- Home /
Getting NullReferenceException when setting the rotation of my enemy
I'll be short and concise. Here's the script:
using UnityEngine;
public class EnemyAI : MonoBehaviour {
Transform target;
public float moveSpeed = 3;
public int rotationSpeed = 3;
private bool checkPlayerDistance = true;
private float[] playerDistance = new float[4];
private bool isReady;
Transform[] player = new Transform[4];
Transform myTransform;
bool losingHealth;
void Awake()
{
myTransform = transform;
}
void Start()
{
target = player [1];
}
void Update () {
if (checkPlayerDistance) {
for(int i = 0; i < 4; i++){
if(!player[i] == null){
playerDistance[i] = Vector3.Distance(player[i].position, myTransform.position);
}
}
}
if (checkPlayerDistance) {
for(int i = 0; i < 4; i++){
if(Mathf.Min(playerDistance[0],playerDistance[1],playerDistance[2],playerDistance[3]) == playerDistance[i]){
target = player[i];
if(!isReady)
isReady = true;
}
}
}
if (isReady) {
myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
void OnCollisionEnter(Collision collision){
}
}
Where I get the error is on the part where if(isReady) is, when setting myTransform.rotation. Any guess on what could cause this?
Answer by Jeff-Kesselman · Jun 26, 2014 at 03:21 PM
Based on your description, either myTransform or target is null.
Print them both with Debug.Log right before that line and see.
I actually managed to solve it myself before you answered, but I'll give you the correct answer anyway. The problem was that I had the transform player be private, but I forgot set it to anything. Which I later did by use a for statement and searching for the gameobject's in the scene. Nice and easy.
Your answer
![](https://koobas.hobune.stream/wayback/20220613152548im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Enemy Rotation AI 0 Answers
How do i get this guy to hold his position? 3 Answers
Unity AI Obstacle Avoidance Help 3 Answers
How to work out dogfight rotations for AI 0 Answers
Slerp rotation on collision - C# 2 Answers