- Home /
GameObject.Find not working
I'm trying to get a prefab to detect a player object with the name "FPSController" but it can't find it. The object is definitely active and the rest of the script works without the GameObject.Find, but I can't declare that in the prefab, any help is greatly appreciated. Here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class NavMesh : MonoBehaviour
{
private Transform PlayerPos;
private GameObject player;
private NavMeshAgent navMeshAgent;
void Start(){
}
void Awake(){
navMeshAgent = GetComponent<NavMeshAgent>();
PlayerPos = player.GetComponent<Transform>();
player = GameObject.Find("FPSController");
}
void Update() {
navMeshAgent.destination = PlayerPos.position;
}
}
Answer by Chubzdoomer · Feb 23 at 12:11 AM
One major problem I see right away is that your order of operations inside of Awake is backwards:
Line 23 should come before 21. The reason is that line 21 is attempting to assign PlayerPos a reference player's Transform before a reference to the player object has even been obtained.
Thank you so much, this fixed it, I would have spent ages tinkering before I found something like that.
Your answer
Follow this Question
Related Questions
For Loop and Null referance error Ios Scripting 1 Answer
How can I add or subtract from a variable in a Mathf.Clamp sequence? 1 Answer
Find GameObjects with a true boolean and put them in an array? 1 Answer
Clones not being Destroyed 1 Answer
using a string variable as an argument in gameobject.find() does not work ? 2 Answers