Weapon Switching, is there an easy way?

My player is without a weapon by default. I want him to be able to pick up guns and switch guns.

My first thought was to just make every single gun you can get, a child of his right forearm, and disable them. This way they are hidden in the background and their scripts wont run in the meantime. The game will patiently wait until you hit a pickup, then enable it.

So I place this little code on my pickup, as a test:

 private GameObject _rifle;

        public void OnCollisionEnter(Collision collision)
        {
            _rifle = GameObject.Find("Rifle");
            _rifle.SetActive(true);
        }

Sadly, this doesn’t work. Unity tells me: “Object reference not set to an instance of an object”

It turns out this may be, because Unity can’t find objects that are disabled. So now I’m a little lost about how to work around this issue. Can you guys help me out?

UPDATE:

I got it to work temporarily now with this script:

        public GameObject WeaponGameObject; //The object you want to activate

        private void OnCollisionEnter(Collision collision)
        {
            WeaponGameObject.SetActive(true);
        }
    }

But sadly I feel this is a temporary solution, because if the player is not in the scene when I was designing the level I can’t actually place his weapon in the public game object slot.

Instead to disable the whole GameObject you could only turn the mesh renderer off. Or set the guns active and then use:

public GameObject[] Guns;
// maybe set size in the inspector and drag all in, or:
void initGuns() {
   Gun = new GameObject[10];
   string gBase = "gun_";
   for(int i-0;i<10;i++) {
     Gun[i] = GameObject.Find(gBase+i); // Ex: gun_0
     Gun[i].active=false;
   }
}

and to make the gameobjects active again, use : Gun[curGun].active=true;

UPDATE:

Things that can find inactive gameObjects :

  • transform.Find() or transform.FindChild()

  • transform.GetComponentsInChildren(true)

  • Resources.FindObjectsOfTypeAll()

  • Transform.Find() or Tranform.FindChild()

Finds a child gameobject ,both active and inactive .

transform.Find(“InActiveGameObject_name”)

or

transform.FindChild(“InActiveGameObject_name”)

If name contains a ‘/’ character it will traverse the hierarchy like a path name.

transform.Find(“Child/InActive”)

This also finds inactive gameobjects in child. If you want to include inactive child gameobjects then you must pass true as a parameter.

transform.GetComponentsInChildren (true)

This will find all the gameobjects with Transform component in child.

This will find all the gameobjects in the current scene , be it active or inactive.

Resources.FindObjectsOfTypeAll()

Credits: www.unityrealm.com/how-to-find-inactive-gameobject-in-unity/

1 Like