- Home /
object reference not set to an instance of an object
Hey there. I have been over this question forwards and backwards and at this point I feel like I'm just overlooking something small. I'm trying to make it so if there are no turrets in the game, the ai will target the player, otherwise, target the turrets. here is my script:
public class Enemy_Turret : MonoBehaviour {
Transform turret;
Transform player;
EnemyHealth enemyHealth;
NavMeshAgent nav;
public float wait;
public bool hurt;
// Use this for initialization
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
turret = GameObject.FindGameObjectWithTag("Turret").transform;
enemyHealth = GetComponent<EnemyHealth>();
nav = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
if (GameObject.Find("Tower Menu").GetComponent<TowerMenu>().tInGame >= 1)
{
nav.SetDestination(turret.position);
}
else if (GameObject.Find("Tower Menu").GetComponent<TowerMenu>().tInGame == 0)
{
nav.SetDestination(player.position);
}
The error I keep running into is when the object spawns, it says that nav.SetDestination(player.position); is not set to an instance of an object. I have also tried just using "else" instead of "else if." I literally have no idea what I'm doing wrong at this point. Any help would be much appreciated.
Answer by KazYamof · Apr 26, 2016 at 11:58 AM
Make sure this script is attached to a game object with a NavMeshAgent component, because when you are probably getting a null reference when you do nav = GetComponent<NavMeshAgent>();
To avoid this kind o error (component dependecy), write above the name of the class the follwing: RequeireComponent(typeof(NavMeshAgent))]
. Now everytime you add your Enemy_Turret component to a game object, a NavMeshAgent will be automaticaly added too.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
NavMeshAgent, goes to the wrong place 0 Answers
Make NavMesh move to random positions 1 Answer
How do you turn an empty game object into a NavMeshAgent target? 1 Answer