Tracking the conversion of a game object. Why is using FindGameObjectWithTag not working?

I am following a tutorial (namely a survival shooter ), and I am at the implementation stage of NavMesh. Their original script is as follows:

 Transform _player;
 NavMeshAgent nav;

 void Start()
 {
     _player = GameObject.FindGameObjectWithTag("Player").transform;
     nav = GetComponent<NavMeshAgent>();
 }

 void Update()
 {
     nav.SetDestination(_player.position);     
 }

Nothing special yet. I press the game and, oddly enough, the enemy (I have only one at the moment on the stage) reaches the initial position of the player (0,0,0) instead of following him if the player moves. I realized that the player’s position is not updated in the field _player, and it stays on 0,0,0.

I tried a different approach: I dragged the Player game object onto a property in the user interface (first I made the property public, and I changed it to GameObject). In this case, it works flawlessly:

 GameObject _player;
 NavMeshAgent nav;

 void Start()
 {
     //Player is not retrieved here as before, but it passed assigning the GameObject to the property directly through the UI
     nav = GetComponent<NavMeshAgent>();
 }

 void Update()
 {
     nav.SetDestination(_player.transform.position);     
 }

:

FindGameObjectWithTag GameObject? . , Unity 5.

+4
2

, , "Player" . , .

Transform _player;
NavMeshAgent nav;

void Start()
{
    GameObject[] playerObjects = GameObject.FindGameObjectsWithTag("Player");
    if(playerObjects.Length>1) 
    {
        Debug.LogError("You have multiple player objects in the scene!");
    }
    _player = playerObjects[0].transform;
    nav = GetComponent<NavMeshAgent>();
}

void Update()
{
    nav.SetDestination(_player.position);     
}
+1

, :

, :

  • : GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();

  • gameObject ,

Transform playerTransform = GameObject.Find("MyPlayerName").transform

  • , script , gameObject this

  • script , script. . :

public GameObject myPlayer;

  • , GameObject.FindGameObjectWithTag, . , - MyFantasticPlayer. :

    `GameObject myPlayer = GameObject.FindGameObjectWithTag("Player");
    if(myPlayer.name == "MyFantasticPlayer")
    {
       Debug.Log("Not problem with FindGameObjectWithTag");
    }else{
    Debug.Log("Problem");
    }`
    

Debug , , .

0

All Articles