Hello. I am trying to make the enemies in my game follow the player. This is my script, but it is not working, what can be done to fix it? Thanks
transform.Translate(GameObject.FindWithTag("Player").transform.position; * 40);
Answer by Jesse Anders
Jan 14, 2011 at 04:40 AM
You don't want to be searching by tag on a per-update basis if you can avoid it. Instead, grab a reference to the player game object or transform in Start() or Awake() and just use that.
Your code has a syntax error in it, so it's not going to compile anyway. (As such, I'm not sure how you've determined whether it's working or not :)
Translating by the player's position is unlikely to do anything meaningful.
There are several ways you can get one object to follow another. Here's one (untested):
Vector3 direction = player.position - transform.position;
transform.position += direction * speed * Time.deltaTime;
Note that this assumes the positions of the two objects will never be the same or nearly the same.
Thanks you for your help. I get an error telling me to put a semi-colon in between "Vector3" and "direction". When I do that, I get an error telling me that "statements must only be executed for their side-effects.".
his code is in C# while urs is in JS. I suppose u just nid to declare var direction : Vector3 instead of Vector 3 direction. maybe that is the problem
Yes, I think the declaration of/assignment to the variable 'direction' will be the only thing you'd need to change in order for the code to work as UnityScript. (I think.)
would it be something like this (basic questions...I know)?
var player : Transform;
var direction : Vector3 = (player.position - transform.position);
That's a little hard to follow. Maybe you could add the question as an edit to your post (or, since it seems this might end up requiring some discussion to get right, maybe just post a new thread to the forums).
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a user guide.
If you are a new user, check out our FAQ for more information.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
For troubleshooting common problems with Unity 5.x Editor (including Win 10).
Answers and Comments
No one has followed this question yet.
why ragged ( not smooth) movement....hlp plz
camera repositions itself
Unity make a bird fly
Vector3.Lerp not working?
C#: Why does this strange jittering occur??