I want it so that if my player holds down the fire button, the gun will be automatic firing so that if I hold the trigger the gun will keep shooting, any way to do that (with fire rate) with this script? On my image the top is my XR grab interactable. The button I use to fire is my trigger.XR grab interactable on top, gun script on bottom
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{ public float speed = 40; public GameObject bullet; public Transform barrel; public AudioSource audioSource; public AudioClip audioClip; public void Fire() { GameObject spawnedBullet = Instantiate(bullet, barrel.position, barrel.rotation); spawnedBullet.GetComponent<Rigidbody>().velocity = speed * barrel.forward; audioSource.PlayOneShot(audioClip); Destroy(spawnedBullet, 2); }
} 3 1 Answer
In your case you already have to events: OnActivate and OnDeactivate so you could modify your code like this
public class Gun : MonoBehaviour
{ public float speed = 40; public GameObject bullet; public Transform barrel; public AudioSource audioSource; public AudioClip audioClip; // configure shots per second public float rate = 1; private Coroutine _current; public void BeginFire() { if(_current != null) StopCoroutine(_current); _current = StartCoroutine (FireRoutine ()); } public void StopFire() { if(_current != null) StopCoroutine(_current); } private IEnumerator FireRoutine() { while(true) { GameObject spawnedBullet = Instantiate(bullet, barrel.position, barrel.rotation); spawnedBullet.GetComponent<Rigidbody>().velocity = speed * barrel.forward; audioSource.PlayOneShot(audioClip); Destroy(spawnedBullet, 2); yield return new WaitForSeconds (1f / rate); } }
}And then as so far in OnActivate call the BeginFire and in the OnDeactivate call the StopFire