C# How to call a function in only one of many prefab clones?
I'm making a space shooter game similar to Galaga where the enemies above you shoot at you randomly. The enemy prefab is cloned multiple times (all with a unique name; enemyclone1-enemyclone8) and all share the same script. Inside of that script is the function to shoot. I want to pick a random clone and call the shoot function so only he shoots a projectile. Is this possible?
Here's what i have:
Enemy Script
public void shoot() //Shoots laser down from enemy's current position
{
Instantiate(laser, transform.position, Quaternion.identity);
GetComponent<AudioSource>().Play();
}
}
Game Manager Script
void shipToShoot()
{
int random = Random.Range(0,onscreenShips); //Picks random enemy ship number
var shooter = GameObject.Find("enemyclone" + random); //Sets shooter equal to random enemy
shooter.GetComponent<Enemy_S>().shoot(); //Makes enemycloneX shoot?
}
When I do this I get these errors

This is where I'm stuck. Any help is GREATLY appreciated.
Answer by UsmanAbbasi · May 12, 2016 at 07:02 AM
The problem is here: Instantiate(laser, transform.position, Quaternion.identity);
"laser" variable is null. Make sure you have assigned the prefab to laser from inspector or through "Resources.Load()".
Thanks! I had it set to static so it wasn't showing in the inspector.
Answer by $$anonymous$$ · May 12, 2016 at 07:14 AM
My suggestion would be to make a list of Enemy_s and use the following code
Enemy_s[] Enemies = GetComponentsInChildren<Enemy_s>();
int onscreenShips = gameobjects.Length;
if (onscreenships > 0)
{
int random = Random.Range(0,onscreenShips);
Enemies[random].shoot();
}
It avoids using the Find function often, which is bad for performance;
Your answer