加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 跟踪游戏对象变换 – 为什么使用FindGameObjectWithTag不

发布时间:2020-12-15 22:16:55 所属栏目:百科 来源:网络整理
导读:我正在学习一个教程(恰好是 survival shooter),我正处于实现NavMesh的阶段.他们原来的脚本是这样的: Transform _player; NavMeshAgent nav; void Start() { _player = GameObject.FindGameObjectWithTag("Player").transform; nav = GetComponentNavMeshAge
我正在学习一个教程(恰好是 survival shooter),我正处于实现NavMesh的阶段.他们原来的脚本是这样的:

Transform _player;
 NavMeshAgent nav;

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

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

到目前为止没什么特别我按下游戏,奇怪的是敌人(我场景中只有一个)只到达玩家的初始位置(0,0),而不是在玩家移动时跟随它.我意识到播放器的位置没有在_player字段中更新,它保持在0,0.

我尝试了一种不同的方法:我将玩家的游戏对象拖放到UI中的属性上(我首先公开了属性,然后将其更改为GameObject).在这种情况下,它完美无缺:

GameObject _player;
 NavMeshAgent nav;

 void Start()
 {
     //Player is not retrieved here as before,but it's 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.

解决方法

您可能在场景中有多个带有“播放器”标记的对象.我更改了您的代码以检测此情况.

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);     
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读