- Home /
Ignoring first move point
Hello, I just started doing tower defense game and as first I am trying to do enemy movement. But the thing is, that enemies after instantiate skip first point to move and goes straight to 2nd, then to 3rd as they should. But can't figure out why they skip that first point... Here is the script:
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class EnemyMovement : MonoBehaviour {
public float movementSpeed;
public List<Transform> movePoints;
private int _index;
private Vector3 _moveDirection;
void Start() {
GameObject[] pointsToMove = GameObject.FindGameObjectsWithTag("MovePoint");
foreach(GameObject ptm in pointsToMove) {
movePoints.Add(ptm.transform);
}
_index = 0;
_moveDirection = (movePoints[_index].position - transform.position).normalized;
}
void FixedUpdate() {
transform.position += _moveDirection * movementSpeed * Time.deltaTime;
}
void OnTriggerEnter(Collider other) {
if(other.tag == "MovePoint") {
_index++;
if(_index == movePoints.Count-1) {
Destroy(gameObject);
}
else {
_moveDirection = (movePoints[_index].position - transform.position).normalized;
}
}
}
}
And here is a picture:
Can you confirm which objects are tagged with $$anonymous$$ovePoint
- is it the three movement points and nothing else (i.e. not spawnPoint
I can see along side the movement points in the editor). It's possible they're colliding with that when they spawn.
spawnPoint is an empty game object without any collider... At the same time only Position1,2,3 are tagged as $$anonymous$$ovePoint. Nothing else.
Is the collision code actually being hit when they spawn and ignore point 1? Stick a Debug.Log line in and see if it's being called at all. I suspect what's actually going on is that the points just aren't in the right order.
I just added more $$anonymous$$ovePoints and realized that you are right. $$anonymous$$ovePoints are indeed not added to the list in the right order. That was the problem. $$anonymous$$ake your comment as answer please. And thank you!
Answer by Jenesis · May 02, 2014 at 09:38 AM
GameObject.FindGameObjectsWithTag
doesn't make any guarantees about the order it'll return its results in. So what's happening is that Point2 ends up first in the list and the enemies are moving straight to that point.
Ordering the points shouldn't be too hard - see answers to this question. I'd go with the 'find them all and then sort them' method rather than searching for them all individually by name, which will be a pain, especially if you add more.
Your answer
![](https://koobas.hobune.stream/wayback/20220613144056im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Destory/Collect object to open door 1 Answer
Distribute terrain in zones 3 Answers
TriggerExit not working as intended/Transforming GameObject Problems 0 Answers
Multiple Cars not working 1 Answer
Door Between Scenes 3 Answers