'Playing Animation, Particle Effect, and Sound only once per second
I've been building a small FPS game project and have working code that plays animations, sound effects, and a muzzle flash effect. I've tried to limit shooting to once per second, but while this works for my shooting Raycast itself, the animation, sound and ParticleSystem I have on line 75-79 don't follow the Time.time interval I've set. Could use some assistance figuring out how to properly time these out for my game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Gun : MonoBehaviour
{
public int id;
public int activeID;
float nextTimeToFire;
AudioSource audioSource;
public ParticleSystem shoot;
[SerializeField] int currAmmo;
[SerializeField] Text ammoCounter;
[SerializeField] AudioClip shootClip = null;
[SerializeField] AudioClip reloadClip = null;
float reloadSpeed = 1f;
bool reloading = false;
public GameObject gameController;
public ItemDatabase database;
public Camera mainCam;
Animator anim;
void Start()
{
gameController = GameObject.FindGameObjectWithTag ("GameController");
database = gameController.GetComponent<ItemDatabase> ();
mainCam = Camera.main;
id = GetComponent<ItemID> ().itemID;
anim = GameObject.FindGameObjectWithTag("Player").GetComponentInChildren<Animator>();
audioSource = GetComponent<AudioSource>();
currAmmo = database.weapons[id].maxAmmo;
}
void Update()
{
if(Input.GetKeyDown(KeyCode.R) && !reloading)
{
if(currAmmo == database.weapons[id].maxAmmo)
{
return;
}
else
{
StartCoroutine(Reload());
return;
}
}
if(Input.GetMouseButtonDown(0) && Time.time >= nextTimeToFire && currAmmo > 0)
{
if(id == activeID)
{
Shoot();
}
}
Ammo();
}
void Shoot()
{
Vector3 rayOrigin = mainCam.ViewportToWorldPoint(new Vector3(0.5f,0.5f, 0));
nextTimeToFire = Time.time + 1f;///database.weapons [id].fireRate;
currAmmo--;
anim.SetTrigger("Attack");
shoot.Play();
audioSource.Stop();
audioSource.clip = shootClip;
audioSource.Play();
RaycastHit hit;
if(Physics.Raycast(rayOrigin, mainCam.transform.forward, out hit, database.weapons [id].range))
{
if (hit.transform.tag == "Enemy")
{
Debug.Log (hit.transform.name);
CharacterStats enemyStats = hit.transform.GetComponent<CharacterStats> ();
enemyStats.TakeDamage (database.weapons [id].damage);
Debug.Log (database.weapons [id].damage);
}
}
}
IEnumerator Reload()
{
audioSource.Stop();
audioSource.clip = reloadClip;
audioSource.Play();
reloading = true;
yield return new WaitForSeconds (reloadSpeed);
currAmmo = database.weapons [id].maxAmmo;
reloading = false;
}
void Ammo()
{
ammoCounter.text = currAmmo.ToString("0");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
