c# - Tracking a game object transform - Why using FindGameObjectWithTag doesn't work? -
i'm following tutorial (precisely survival shooter), , @ stage implement navmesh. original script this:
transform _player; navmeshagent nav; void start() { _player = gameobject.findgameobjectwithtag("player").transform; nav = getcomponent<navmeshagent>(); } void update() { nav.setdestination(_player.position); }
so far nothing special. press play , strangely enemy (i have 1 @ moment in scene) reaches initial position of player (0,0,0) instead of following around if player moves. realized position of player not updated in _player
field , stays @ 0,0,0
.
i tried different approach: dragged , dropped player's game object onto property in ui (i made property public first , changed gameobject
). in case works flawlessly:
gameobject _player; navmeshagent nav; void start() { //player not retrieved here before, it's passed assigning gameobject property directly through ui nav = getcomponent<navmeshagent>(); } void update() { nav.setdestination(_player.transform.position); }
at stage wonder:
does findgameobjectwithtag
method make copy of object instead of returning reference gameobject
? why doesn't work in first instance. use unity 5 way.
you have more 1 object tag "player" in scene. changed code detect condition.
transform _player; navmeshagent nav; void start() { gameobject[] playerobjects = gameobject.findgameobjectswithtag("player"); if(playerobjects.length>1) { debug.logerror("you have multiple player objects in scene!"); } _player = playerobjects[0].transform; nav = getcomponent<navmeshagent>(); } void update() { nav.setdestination(_player.position); }
Comments
Post a Comment