Im making a TD game with multiple towers, and ofc multiple enemies.
so far ive used the targetting system for towers to call up
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy")
then draw a line from my tower to the enemy
GameObject target = enemies[0] // target first enemy
LineRenderer lr = GetComponent<LineRenderer>();
lr.SetPosition(0,this.transform.position);
lr.SetPosition(1,target.transform.position);
and this seems to work fine. Its just that the FindGameObjectsWithTag seems to be a little resource demanding. Therefore i want an object to hold the list of enemies, and every enemy reporting to this object by a public function
public void AddEnemy(GameObject enemy)
{
enemies.Add(enemy);
}
(Im using a List since i figured this was the easiest for adding enemies, since i cant have it fixed size)
but when I get the list back from this GameObject, the enemies[0].transform.position is always equal to the spawnpoint of that enemy, basicly making the lines point towards spawn.
UPDATING with more code
The Spawner class
public float spawnTime = 3;
public GameObject enemy;
public GameObject target;
GameObject game;
Game gamescript;
float timer;
// Use this for initialization
void Start () {
timer = 0;
game = GameObject.FindGameObjectWithTag("Game");
gamescript = game.GetComponent<Game>();
}
// Update is called once per frame
void Update () {
timer += Time.deltaTime;
if(timer>spawnTime)
{
enemy.transform.position = gameObject.transform.position;
enemy.GetComponent<AIPath>().target = target.transform;
Instantiate(enemy);
gamescript.AddEnemy(enemy);
timer = 0;
}
}
then the class holding the list of enemies
public List<GameObject> enemies;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(enemies.Count > 0)
{
Debug.Log(enemies[0].transform.position);
// this returns the spawnpoint
}
}
public void AddEnemy(GameObject enemy)
{
enemies.Add(enemy);
}
This is where my code goes wrong. I’m sure that if i can fix it here, the rest will solve itself, but i really cant see what im doing wrong. ive also tried to add this.gameobject from the enemy class but same problem there