0
votes

I am making a space invaders game, and have a script attached to a separated gameObject that instantiates Enemies. I can drag in the prefab and make it work, but then I want the enemies to spawn bullets themselves, with the bullet being a prefab.

I have started with just creating a variable for the bullet, but how would I access the prefab in script, as if I just drag it into the prefab, it won't be useable after the prefab is instantiated.

GameObject bullet;

void Start() {
    bullet = // Insert Function to access prefab
}

Thanks

2

2 Answers

1
votes

If you put your prefab in a Root Folder named "Resources" you can load prefabs from there like this:

Instantiate(Resources.Load("YourBulletPrefab"));

But you can also make the variable public...

public GameObject bullet; // or use private + [SerializeField]

...and then in Inspector, drag your Prefab in. No need to initialize it in Start() in that case.

1
votes

I usually solve this by adding a public GameObject bullet variable to the "enemy" script AND the "enemy spawner" script. In the inspector you give reference to the "enemy spawner" to access the bullet prefab. And then, when you spawn an enemy, you pass its reference to the enemy. Something like this:

Enemy script:

class Enemy
{
   public GameObject bullet;

   private Shoot()
   {
       //Shoot bullet
   }    
}

EnemySpawner script:

class EnemySpawner
{
   public GameObject enemy;
   public GameObject bullet;

   private Spawn()
   {
       GameObject newEnemy = Instantiate(enemy);
       enemy.GetComponent<Enemy>().bullet = bullet;
   }    
}

By doing so, you will be able to access the bullets later as well.