Issues with prefabs/Instantiating

I’m certain this isn’t the best way to handle this but its what I came up with on my own. But when I open the chest it sometimes spawns 1 Gun and sometimes spawns 2 or more, any insight is appreciated.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PistolChestScript : MonoBehaviour
{
    public Animator anim;
    public bool chestIsOpen;
    public GameObject Gun;
    public Transform gunHolderLocation;
    public Transform gunHolderRotation;
  
    // Start is called before the first frame update
    void Start()
        {
            chestIsOpen = false;
        }

    // Update is called once per frame
    void Update()
        {
            if(chestIsOpen == true)
            {
                gameObject.GetComponent<BoxCollider>().enabled = false;
              
            }
        }
  
    void OnTriggerStay(Collider other)
        {
            if(other.tag == "Player" && Input.GetKeyDown(KeyCode.E))
            {
                Debug.Log("You Got a Pistol");
                Instantiate(Gun, gunHolderLocation.position, gunHolderRotation.rotation);
                chestIsOpen = true;
                anim.Play("ChestLidAnimation");
               
            }
        }  
}
if(other.tag == "Player" && Input.GetKeyCode(KeyCode.E))

if(!chestIsOpen && other.tag == "Player" && Input.GetKey(KeyCode.E))

This is because the OnTriggerStay will be continuous (in every frame), the tag is constant and the GetKey (I assume you only mistyped this here on the forum) is returning true also continuously while the key is pressed.

Thank you very much.

I also would move this line:

gameObject.GetComponent<BoxCollider>().enabled = false;

into this if. After that the entire Update method can be removed (if you don’t have anything else in it).

Perfect, thank you again

1 Like