Home > Software engineering >  How Can I Make This Debounce Script Work? Unity3D
How Can I Make This Debounce Script Work? Unity3D

Time:02-04

This is my script, when I click the debounce works at first, but after the wait you can just spam click and shoot many bullets at once. How can I fix this? I am a beginner so any help will be nice :) I had to get rid of some because stack overflow wasn't happy

using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SingleShotGun : Gun
{
    [SerializeField] Camera cam;

    PhotonView PV;

    public bool debounce = false;

    public float debounce2;

    public AudioSource audioSource;
    public AudioClip audioClip;

    private float timeStarted;
    private float audioTime;

    private void Start()
    {
        if (PV.IsMine)
        {
            audioSource.clip = audioClip;
            float timeStarted = (float)PhotonNetwork.Time;
            audioTime = 0;
        }
    }

    private void Update()
    {
        if (PV.IsMine)
        {
            float audioTime = (float)PhotonNetwork.Time - timeStarted;
        }
        else
        {
            audioSource.time = audioTime;
        }
    }

    void Awake()
    {
        PV = GetComponent<PhotonView>();
    }

    public override void Use()
    {
        if (debounce)
        {
            StartCoroutine(Deb());
            return;
        }
        if (PV.IsMine)
        {
            audioSource.clip = audioClip;
            float timeStarted = (float)PhotonNetwork.Time;
        }
        debounce = true;
        Shoot();
    }

    private IEnumerator Deb()
    {
        Debug.Log("Debouncing");
        yield return new WaitForSeconds(debounce2);
        debounce = false;
    }
}

I Tried to make a debounce script for unity3d, but it didn't work?

CodePudding user response:

As a first note: in

float audioTime = (float)PhotonNetwork.Time - timeStarted;

you are creating a new local variable => the class field audioTime is not assigned in that case

same also for all occurrences of

float timeStarted = (float)PhotonNetwork.Time;

you want to remove the float in all three places in order to rather assign your class fields instead of over shadowing them with same named local variables, otherwise they will always have the default value 0.


Then within Use you are starting multiple concurrent routines that will all finish eventually and reset your debounce in unexpected moments. You probably rather want to wrap it in order to start only a single routine like

if(!debounce)
{
    debounce = true;
    Shoot();
    StartCoroutine(Deb()):
}

Also again in general I would expect the entire Use should be wrapped in / start with

if (!PV.IsMine) return;

as it looks and sounds like none of those things should happen at all if this is not your gun ;)

And after setting

audioSource.clip = audioClip;

you also need to

audioSource.Play();
  • Related