I have a GameObject (HandGun) which I disable (setActive(false)) in a certain moment of the game. HandGun has a script attached to it named GunController, which takes care of shooting everytime I press the trigger.
The thing is, when I disable the HandGun, I can still shoot and see the bullet coming out of nothing, because the HandGun GameObject is successfully gone.
GunController script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EZEffects;
public class GunController : MonoBehaviour {
public GameObject controllerRight;
public AudioClip clip;
AudioSource sound;
public int damage;
private SteamVR_TrackedObject trackedObj;
public SteamVR_Controller.Device device;
private SteamVR_TrackedController controller;
public EffectTracer TracerEffect;
public EffectImpact ImpactEffect;
public Transform muzzleTransform;
// Use this for initialization
void Start () {
sound = gameObject.AddComponent<AudioSource>();
controller = controllerRight.GetComponent<SteamVR_TrackedController>();
controller.TriggerClicked += TriggerPressed;
trackedObj = controllerRight.GetComponent<SteamVR_TrackedObject>();
device = SteamVR_Controller.Input((int)trackedObj.index);
}
private void TriggerPressed(object sender, ClickedEventArgs e)
{
shootWeapon();
}
public void shootWeapon()
{
sound.PlayOneShot(clip,0.2f);
RaycastHit hit = new RaycastHit();
Ray ray = new Ray(muzzleTransform.position, muzzleTransform.forward);
device.TriggerHapticPulse(3999);
TracerEffect.ShowTracerEffect(muzzleTransform.position, muzzleTransform.forward, 250f);
if(Physics.Raycast(ray, out hit, 5000f))
{
if (hit.collider.attachedRigidbody)
{
Enemy enemy = hit.collider.gameObject.GetComponent<Enemy>();
if (enemy)
{
enemy.TakeDamage(damage);
}
ImpactEffect.ShowImpactEffect(hit.transform.position);
}
}
}
// Update is called once per frame
void Update () {
}
}
Part of the Inspector script, which is who disables the HandGun gameobject:
public void showShop()
{
shop.SetActive(true);
shopActive = true;
if (actualGun == null)
{
actualGun = handGun;
}
actualGun.SetActive(false);
model.SetActive(true);
}
Moreover, if I deactivate the GunController script manually when the game is running, I can still shoot, which I absolutely don't understand. I'm using EZEffect which can be found on the unity store.
What am I doing wrong? What should I do?
Anyway, thank you in advance for your help!
A script can still execute code when it is on a disabled gameobject.
However the Update Function will not fire. Seeing as your GunController does not utilize its Update(), I suspect that your Input Listener is somewhere else (Probably EZEffect?).
To prevent your controller from firing, you could add a check to your code.
private void TriggerPressed(object sender, ClickedEventArgs e)
{
if (gameobject.ActiveSelf)
{
shootWeapon();
}
}
Or you can disable the script listening for User Input