Loading a new GameObject in place of another (Weapon Switch)

Hello guys.

I am making a space ship shooter game.

I have one problem. Mainly:

  1. I have player ship Game Object and a script assigned to it holding the PlayerBullet Game Object
  2. Now whenever player touches swap game object (CollisionEnter) I want the PlayerBullet Game Object to become another bullet from my prefabs.

Here is part of code:

public class PlayerControls : MonoBehaviour {

public GameObject PlayerBulletGO;   // my starting bullet - assigned to me in Unity via script

}
//then I want it to switch here:

void OnTriggerEnter2D(Collider2D col)
{
if(col.tag == “GreenWeaponTag”)
{
PlayerBulletGO = GameObject.Find(“GreenWeapon”);
}
}

Not working how I want - do my green weapon gameobject need to be in scene?

Any ideas?
Thanks :slight_smile:

If you do it like that, then yes, it has to be in the scene. GameObject.Find searches the scene for objects with the name you send in, and returns you the first one it finds with that name.

That’s not an ideal way to do it, though. It’s a lot easier to just have some other public fields, and assign the bullet prefabs to them. Then you can just switch to the correct field:

public class PlayerControls : MonoBehaviour {

     public GameObject PlayerBulletGO;   // assign the starting bullet here
     public GameObject greenWeapon; //assign the green weapon here.

     void OnTriggerEnter2D(Collider2D col) { 
         if(col.tag == "GreenWeaponTag") { 
             PlayerBulletGO = greenWeapon;
         }
    }
}