- Home /
This question was
closed Dec 16, 2018 at 06:26 PM by
el-mas-pro-470 for the following reason:
the answer given does not work.
Question by
el-mas-pro-470 · Dec 16, 2018 at 03:37 AM ·
c#raycastshootingammoweapon system
Limited ammo from Raycast?
Hello! how to have limited ammo from this script? Thanks!
using UnityEngine;
using System.Collections;
public class Weapon : MonoBehaviour {
public float Damage = 0f;
public float Range = 0f;
public float ImpactForce = 0f;
public float FireRate = 0f;
public int MaxAmmo = 0;
public int CurrentAmmo;
public float ReloadTime = 0;
private bool IsReloading = false;
public Camera FPScam;
public ParticleEmitter MuzzleFlash;
public GameObject HitEffect;
private float NextTimeToFire = 0f;
public Animator Animators;
public AudioClip ShootSound;
void Start()
{
CurrentAmmo = MaxAmmo;
}
void OnEnable()
{
IsReloading = false;
Animators.SetBool("Reloading", false);
}
void Update () {
if(IsReloading)
return;
if(CurrentAmmo <= 0)
{
StartCoroutine(Reload());
return;
}
if(Input.GetButton("Fire1") && Time.time >= NextTimeToFire)
{
NextTimeToFire = Time.time + 1f/FireRate;
Shoot();
}
}
IEnumerator Reload()
{
IsReloading = true;
Debug.Log("Reloading...");
Animators.SetBool("Reloading", true);
yield return new WaitForSeconds(ReloadTime - 0.25f);
Animators.SetBool("Reloading", false);
CurrentAmmo = MaxAmmo;
IsReloading = false;
}
void Shoot()
{
audio.Play();
audio.clip = ShootSound;
MuzzleFlash.Emit();
CurrentAmmo--;
RaycastHit hit;
if (Physics.Raycast(FPScam.transform.position, FPScam.transform.forward, out hit, Range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if(target != null)
{
target.TakeDamage(Damage);
}
if(hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * ImpactForce);
}
Instantiate(HitEffect, hit.point, Quaternion.LookRotation(hit.normal));
}
}
}
Comment
Answer by fuzzy_rick · Dec 16, 2018 at 04:21 AM
Add a new variable for totalAmmo. Reduce it by maxammo when you reload. Check if it's zero before reloading
ok, at the top of reload add "if (totalammo==0) return;"
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Raycast shooting for multiple weapons 1 Answer
shooting multiple enemies using raycast 2 Answers
Enemy Shooting Through Raycasts 0 Answers