I want to make my unity gun script for vr be automatic, any way to do it with this script?

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like