- Home /
C# - Ammo in Shoot Array?!
I need to implement ammo/reload function. How would i do this in my script?
using UnityEngine;
public class Shooter : MonoBehaviour
{
void Update ( )
{
// 1. Wait for a mouse click.
if ( Input.GetButtonDown( "Fire1" ) )
{
Shoot( );
}
}
void Shoot ( )
{
// 2. Create a ray that travels from your camera
// in the direction it's facing.
Ray ray = new Ray( transform.position, transform.forward );
RaycastHit hit;
if ( Physics.Raycast( ray, out hit ) )
{
// 3. Check the first thing it hits, is it your enemy?
// If so (actually there is nothing defined as enemy);
hit.transform.SendMessage( "OnBullet",
SendMessageOptions.DontRequireReceiver );
}
}
}
Comment
Answer by aldonaletto · Dec 13, 2012 at 11:36 PM
You must keep track of how many bullets you have. Usually you count the bullets currently in your weapon: when they reach zero, reload the weapon with a new clip, which contains a fixed and predefined number of bullets. When the bullets in your gun are over, play the reload sound and wait the reload time before actually reloading the bullets variable - like this:
using UnityEngine;
public class Shooter : MonoBehaviour
{
public AudioClip shotSound;
public AudioClip reloadSound;
public AudioClip clickSound; // optional "no bullets" click sound
public int clips = 2; // how many clips you have
public int bulletsPerClip = 20; // how many bullets per clip
public int bullets = bulletsPerClip; // start with a brand new clip in the gun
public float reloadTime = 0.5f; // reload time in seconds
void Update ( )
{
// 1. If Fire button pressed...
if ( Input.GetButtonDown( "Fire1" ) ){
if (bullets > 0){ // and you have bullets...
Shoot( ); // shoot
}
else // but if gun empty...
if (clips > 0){ // and still have ammo clips...
StartCoroutine(Reload()); // start reload routine
}
else // no bullets, no clips:
if (clickSound){ // play a click sound, if desired
audio.PlayOneShot(clickSound);
}
}
}
private bool reloading = false; // is true while reloading, false otherwise
IEnumerator Reload(){
// abort other Reload calls if already reloading:
if (reloading) return null;
reloading = true; // signals that is currently reloading
clips -= 1; // got one clip, decrement clip count:
audio.PlayOneShot(reloadSound); // play the reload sound
yield new WaitForSeconds(reloadTime); // wait the reload time
bullets = bulletsPerClip; // now the bullets are available
reloading = false; // reloading finished
}
...
Your answer
Follow this Question
Related Questions
Reload manually in raycast? 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers