- Home /
Get position of prefab enemy ?
Hello,
I have a prefab of enemies who spawn regularly. I try to get the position of them in order to kill them. It work with the one already instanciate but not the new.
First I get the gameobject and the position from the enemy script:
public GameObject Foe = GameObject.Find("o_foe"); public float PosXFoe; public float PosZFoe;
Then:
void Start() {
Foe = GameObject.FindGameObjectWithTag("Foe");
FoeHealth = Foe.GetComponent<s_EnnemyControl>();
}
void Update() {
PosXFoe = GameObject.Find("o_foe").GetComponent<s_EnnemyControl>().PosXFoe - 2;
PosZFoe = GameObject.Find("o_foe").GetComponent<s_EnnemyControl>().PosZFoe - 2;
}
And the attack:
void GestureAttack()
{
if (recupgeste == "D" && recupgestescore > 0.50)
{
player.transform.position = new Vector3(PosXFoe, 1, PosZFoe);
if (FoeHealth.currentHealth > 0 /*attackphas*/)
{
// ... damage the player.
FoeHealth.TakeDamage(attackDamage);
}
}
}
Help me, thanks.
Avoid using GameObject.Find. Ins$$anonymous$$d, keep a list of instantiated enemy gameobjects, and add or remove from it when you instantiate and destroy them. This way, you always have a reference to each one that's currently in the scene.
Also note that if you instantiate a clone of a prefab, " Clone(0)" or something along that line will be added to the clone's name, so GameObject.Find won't help you in those cases if you don't manually change the clone's name back to the prefab's name.
Cherno has it right.
You can use a List for keeping track of all your creations or simply a variable to keep reference to the last enemy created.
With a list you can do the following:
import System.Collections.Generic; //Helps you use List
public List enemies;
public GameObject lastEnemySpawned;
public GameObject enemyPrefab; //In inspector drag and drop your enemy prefab onto this.
public class SomeClass
{
//Create your list on awake or start
void Awake()
{
enemies = new List<GameObject>();
}
//Spawn your enemy and keep a reference for it, then add it to the list of enemies.
private void SpawnEnemy()
{
lastEnemySpawned = (GameObject) Instantiate(myEnemyPrefab, transform.position, transform.rotation);
enemies.Add(lastEnemySpawned);
}
}
I'd like to add that it's necessary to import System.Collections.Generic in order to use Generic Lists.
Your answer
![](https://koobas.hobune.stream/wayback/20220612075944im_/https://answers.unity.com/themes/thub/images/avi.jpg)