[C#] Getting an ally on the players team to go towards a random enemy on the other team?

private Transform enemyPos;

void Update(){

if(enemyPos == null){

Transform[] enemies = gameObject.getComponentsInChildren<Transform>();

if(enemies.Length > 0){

enemyPos = enemies[Random.Range(0, enemies.Length)];

}

}

else{

transform.LookAt(enemyPos);

transform.position += transform.forward * moveSpeed * Time.deltaTime;

}

}

Please see the above, it makes more sense.

Here are some mistakes and explanation. Please let me know if something is not clear and I'll try to explain further.

You don't need to access the enemyPos from the editor, hence the change to private.

You would like to only search for enemies once, not each frame.

You would definitely not want to get a random enemy each frame.

You are looking at the enemy position which you manually assign? The randomObject is effectively useless with your implementation, you're not doing anything with it.

/r/learnprogramming Thread Parent