- Home /
Unknown reason for NullReferenceException error
Just need someone to read over this code and see if they can source the reason for the NullReferenceException error
using System;
using UnityEngine;
public class Enemy : MonoBehaviour
{
Vector3 prevPos;
GameObject player;
Player playerScript;
public Vector3 targetPosition;
public Transform turretF, turretB, turretT;
void Start()
{
player = GameObject.Find("Player");
playerScript = player.GetComponent<Player>();
prevPos = transform.position;
turretB = transform.Find("turretB");
turretT = transform.Find("turretT");
turretF = transform.Find("turretF");
}
void Update()
{
targetPosition = new Vector3(player.transform.position.x, turretB.position.y, player.transform.position.z);
turretB.LookAt(targetPosition);
}
}
The following line is the one that returns the reference error:
targetPosition = new Vector3(player.transform.position.x, turretB.position.y, player.transform.position.z);
Thanks in advance!
Comment
Answer by doublemax · Oct 08, 2016 at 08:54 PM
targetPosition = new Vector3(player.transform.position.x, turretB.position.y, player.transform.position.z);
"player" is already referenced in Start(), so it can't be null. That only leaves "turretB". Now you have to find out why "transform.Find("turretB");" doesn't find the GameObject.
If you don't know how to use a debugger, some Debug.Log() outputs of involved variables are usually enough to spot what's going on.