I have been driving myself crazy and my research is getting me no-where. currentLoc.position returns the correct position in my main script but returns [0,0,0] in the FindNeareasShelf script. Both scripts are attached to the game object and I’d like to make it know that I am also using a prefab spawner on the game object. Please send help.
public class Walk2Target : MonoBehaviour
{
private NavMeshAgent agent;
private Transform Target;
public Transform currentLoc;
private FindNearestShelf[] target;
private void Awake()
{
agent = GetComponent<NavMeshAgent>();
}
private void FixedUpdate()
{
if (Target == null)
{
currentLoc = transform;
Debug.Log(currentLoc.position); // returns correct transform
Target = GetComponent<FindNearestShelf>().target;
}
if (Target != null)
{
agent.destination = Target.position;
}
}
}
public class FindNearestShelf : MonoBehaviour
{
public Transform target;
public void OnEnable()
{
target = FindTarget();
Debug.Log(GetComponent<Walk2Target>().currentLoc.position);// returns [0,0,0]
}
public Transform FindTarget()
{
GameObject[] candidates = GameObject.FindGameObjectsWithTag("Shelf");
float minDistance = Mathf.Infinity;
Transform closest;
if (candidates.Length == 0)
return null;
closest = candidates[0].transform;
for (int i = 1; i < candidates.Length; ++i)
{
float distance = (candidates[i].transform.position - GetComponent<Walk2Target>().currentLoc.position).sqrMagnitude;// have also tries - transform.position but returns [0,0,0]
if (distance < minDistance)
{
closest = candidates[i].transform;
minDistance = distance;
}
}
return closest;
}
}