Weapon pick up (C#)

Hello,
Im working on a script to pick up weapons.
But I run into a few problems…

When Im in the trigger and I press “E” the dummy gets destroyed, but the weapon doesn´t gets activated.
The script is attached to the dummy.

Can someone tell me why this doesn´t work?

Thanks in advanced. :slight_smile:

Code here:

public class PickUpWeapon : MonoBehaviour
{

    public bool inTrigger = false;




    void OnTriggerEnter(Collider collison)
    {
        inTrigger = true;
    }

    void OnTriggerExit(Collider collison)
    {
        inTrigger = false;
    }

    void Start()
    {
        GameObject.Find("Pistol").SetActive(false);  //deactivates pistol
        GameObject.Find("Uzi").SetActive(false);     //deactivates uzi
    }

    void Update()
    {
        if (inTrigger && Input.GetKeyDown(KeyCode.E))
            if (gameObject.tag == "PistolDummy")  //pistoldummy = pick up pistol
                Destroy(gameObject); //destroys dummy
                GameObject.Find("Pistol").SetActive(true);
                GameObject.Find("Uzi").SetActive(false);

        if (gameObject.tag == "UziDummy")  //uzidummy = pick up uzi
                Destroy(gameObject); //destroys dummy
                GameObject.Find("Uzi").SetActive(true);
                GameObject.Find("Pistol").SetActive(false);
    }


}

I don’t think you can use GameObject.Find() on disabled objects (not active). And since it seems you only have one instance of each, I recommend you use public references.
Not only that, your ifs are missing brackets, so they only execute the first line.
Here’s a correction;

public class PickUpWeapon : MonoBehaviour
{

    public bool inTrigger = false;

 
    public GameObject Uzi, Pistol;

    void OnTriggerEnter(Collider collison)
    {
        inTrigger = true;
    }

    void OnTriggerExit(Collider collison)
    {
        inTrigger = false;
    }

    void Start()
    {
        Pistol.SetActive(false); //deactivates pistol
        Uzi.SetActive(false); //deactivates uzi
    }

    void Update()
    {
        if (inTrigger && Input.GetKeyDown(KeyCode.E))
        if (gameObject.tag == "PistolDummy"){ //pistoldummy = pick up pistol
            Destroy(gameObject); //destroys dummy
            Pistol.SetActive(true);
            Uzi.SetActive(false);
        }

        if (gameObject.tag == "UziDummy"){ //uzidummy = pick up uzi
            Destroy(gameObject); //destroys dummy
            Uzi.SetActive(true);
            Pistol.SetActive(false);
        }
    }
}

P.S.: use code tag to make your code readable on forums.

Edit: forgot to get rid of "Find"s

fixed now.

1 Like