1

I have been messing with unity and VR lately and I have been using this code from youtube to fire a gun (https://www.youtube.com/watch?v=kD47gUJO7jA) The gun works fine but the sound it makes repeats fast and sounds awful so I need it to be delayed. I have tried system threading but that stops the app momentarily and can cause nausea I have also tried task.delay in multiple ways and it either doesn't work or unity cannot compile it due to errors. Can someone help me out with this?

using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;

public class ControllerInput : MonoBehaviour
{
    public AudioClip clip;
    public AudioSource audioSource;
    public Transform gunBarrelTransform;

    // Use this for initialization
    void Start()
    {
        audioSource = GetComponent<AudioSource>();
        audioSource.clip = clip;
    }

    // Update is called once per frame
    void Update()
    {
        if (OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger))
        {
            audioSource.Play();
            RaycastGun();
            
        }
    }

    private void RaycastGun()
    {
        RaycastHit hit;

        if (Physics.Raycast(gunBarrelTransform.position, gunBarrelTransform.forward, out hit))
        {
            if (hit.collider.gameObject.CompareTag("Cube"))
            {
                Destroy(hit.collider.gameObject);
            }
        }
    }
}```
Kpmccain
  • 11
  • 1

1 Answers1

0

The problem is that you are calling audioSource.Play on every frame that the trigger is down. You need another test to see whether it's been played too recently. You could use the length of the audio clip, but you might want it to be more or less frequent than that, so let's use an arbitrary float value.

public class ControllerInput : MonoBehaviour
{
    public AudioClip clip;
    public AudioSource audioSource;
    public Transform gunBarrelTransform;
    // ADD THESE FIELDS ↓
    public float minSoundRepeatTime = 0.5f;
    float buttonHoldTime = -1f;

//...
    void Update()
    {
        if (OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger))
        {
            if (buttonHoldTime < 0f || buttonHoldTime > minSoundRepeatTime)
            {
                buttonHoldTime = 0f;
                audioSource.Play();
            }
            buttonHoldTime += Time.deltaTime;
        }
        else buttonHoldTime = -1f;

        RaycastGun();
    }
//...
Joseph
  • 733
  • 1
  • 4
  • 20