- Home /
How do I check the variable of a specific clone?
I am trying to make a game where multiple enemies come down to attack. I Instantiate them and have them randomly come down. But when I check if they are touching a bullet, only the last instantiated enemy can check it.
Here is the code I am using: (The last 2 if statements are supposed to work for all clones but only works for the last instantiated one)
public ButtonManager script;
public GameObject enemy1;
float SpawnTime1 = 0;
public float MaxTime1;
public Enemy1AI script1;
GameObject newEnemy1;
static Enemy1AI staticVar;
void Update()
{
if(script.playingGame == true)
{
SpawnTime1 += Time.deltaTime;
if (SpawnTime1 > MaxTime1)
{
newEnemy1 = Instantiate(enemy1);
newEnemy1.transform.position = new Vector2(Random.Range(-4.8f, 4.8f), 10f);
SpawnTime1 = 0;
MaxTime1 = Random.Range(4, 5);
}
Enemy1AI staticVar = newEnemy1.gameObject.GetComponent<Enemy1AI>();
if (staticVar != null)
{
if (staticVar.transform.position.y < -7)
{
Destroy(newEnemy1);
script.health -= 1;
}
if (staticVar.isTouchingBullet == true)
{
Destroy(newEnemy1);
script.sc += 100;
}
}
}
}
Answer by Caeser_21 · Feb 22 at 12:13 PM
This is happening because you are only checking the script of the last spawned enemy. To counteract this do the following...
1. Create a new tag called "Enemy1" and add it to the 'enemy1' Gameobject.
2. Then change the script to the following...
public ButtonManager script;
public GameObject enemy1;
float SpawnTime1 = 0;
public float MaxTime1;
public Enemy1AI script1;
GameObject newEnemy1;
static Enemy1AI staticVar;
private GameObject[] 1Enemies;
void Update()
{
Enemies = GameObject.FindGameObjectsWithTag("Enemy1")
if(script.playingGame == true)
{
SpawnTime1 += Time.deltaTime;
if (SpawnTime1 > MaxTime1)
{
newEnemy1 = Instantiate(enemy1);
newEnemy1.transform.position = new Vector2(Random.Range(-4.8f, 4.8f), 10f);
SpawnTime1 = 0;
MaxTime1 = Random.Range(4, 5);
}
foreach (GameObject Enemy in 1Enemies)
{
Enemy1AI staticVar = Enemy.gameObject.GetComponent<Enemy1AI>();
if (staticVar != null)
{
if (staticVar.transform.position.y < -7)
{
Destroy(Enemy);
script.health -= 1;
}
if (staticVar.isTouchingBullet == true)
{
Destroy(Enemy);
script.sc += 100;
}
}
}
}
}
NOTE : I have no clue what the 'ButtonManager' script does so I don't know whether to change it or not
Thank you so much! I was stuck on this problem for about an hour, I am very thankful of you.
Your answer
![](https://koobas.hobune.stream/wayback/20220613053331im_/https://answers.unity.com/themes/thub/images/avi.jpg)