Weapon reloading

i need to make a script to where you have to press the “R” key to reload, I don’t have a reload animation for my weapons yet, but i would like a reload function for now, as i am starting the game out.

Thank You!!
Matt

Well, the way you reload a gun really depends on the main gun script you have. Usually you would just reset the current ammo you have for the gun and play an appropriate animation. Usually you would define a key in the input settings that would act as reload, so you could make a script something like:

Update(){
    if(Input.GetButtonUp("Reload")){
        //Reset ammo and play animation
    }
}

Where would i add that in this script?
I tried several places but I can’t get it to work.

var range = 100.0;
var fireRate = 0.05;
var force = 10.0;
var damage = 5.0;
var bulletsPerClip = 40;
var clips = 20;
var reloadTime = 0.5;
private var hitParticles : ParticleEmitter;
var muzzleFlash : Renderer;

private var bulletsLeft : int = 0;
private var nextFireTime = 0.0;
private var m_LastFrameShot = -1;

function Start () {
	hitParticles = GetComponentInChildren(ParticleEmitter);
	
	// We don't want to emit particles all the time, only when we hit something.
	if (hitParticles)
		hitParticles.emit = false;
	bulletsLeft = bulletsPerClip;
}

function LateUpdate() {
	if (muzzleFlash) {
		// We shot this frame, enable the muzzle flash
		if (m_LastFrameShot == Time.frameCount) {
			muzzleFlash.transform.localRotation = Quaternion.AngleAxis(Random.value * 360, Vector3.forward);
			muzzleFlash.enabled = true;

			if (audio) {
				if (!audio.isPlaying)
					audio.Play();
				audio.loop = true;
			}
		} else {
		// We didn't, disable the muzzle flash
			muzzleFlash.enabled = false;
			enabled = false;
			
			// Play sound
			if (audio)
			{
				audio.loop = false;
			}
		}
	}
}

function Fire () {
	if (bulletsLeft == 0)
		return;
	
	// If there is more than one bullet between the last and this frame
	// Reset the nextFireTime
	if (Time.time - fireRate > nextFireTime)
		nextFireTime = Time.time - Time.deltaTime;
	
	// Keep firing until we used up the fire time
	while( nextFireTime < Time.time  bulletsLeft != 0) {
		FireOneShot();
		nextFireTime += fireRate;
	}
}

function FireOneShot () {
	var direction = transform.TransformDirection(Vector3.forward);
	var hit : RaycastHit;
	
	// Did we hit anything?
	if (Physics.Raycast (transform.position, direction, hit, range)) {
		// Apply a force to the rigidbody we hit
		if (hit.rigidbody)
			hit.rigidbody.AddForceAtPosition(force * direction, hit.point);
		
		// Place the particle system for spawing out of place where we hit the surface!
		// And spawn a couple of particles
		if (hitParticles) {
			hitParticles.transform.position = hit.point;
			hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
			hitParticles.Emit();
		}

		// Send a damage message to the hit object			
		hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
	}
	
	bulletsLeft--;

	// Register that we shot this frame,
	// so that the LateUpdate function enabled the muzzleflash renderer for one frame
	m_LastFrameShot = Time.frameCount;
	enabled = true;
	
	// Reload gun in reload Time		
	if (bulletsLeft == 0)
		Reload();			
}

function Reload () {

	// Wait for reload time first - then add more bullets!
	yield WaitForSeconds(reloadTime);

	// We have a clip left reload
	if (clips > 0) {
		clips--;
		bulletsLeft = bulletsPerClip;
	}
}

function GetBulletsLeft () {
	return bulletsLeft;
}

you already got a reload function, just edit around the " If clips are greater than 0, then minus 1 clip and add back in full bullets in clip "

" // We have a clip left reload
if (clips > 0) {
clips–;
bulletsLeft = bulletsPerClip; "

Just put another statement there with " If R pressed "

Im also a newbie at code so i could be wrong

so this is what i did, and i made the input button set to R but when i press R i do not reload

new code is

var range = 100.0;
var fireRate = 0.05;
var force = 10.0;
var damage = 5.0;
var bulletsPerClip = 40;
var clips = 20;
var reloadTime = 0.5;
private var hitParticles : ParticleEmitter;
var muzzleFlash : Renderer;

private var bulletsLeft : int = 0;
private var nextFireTime = 0.0;
private var m_LastFrameShot = -1;

function Start () {
	hitParticles = GetComponentInChildren(ParticleEmitter);
	
	// We don't want to emit particles all the time, only when we hit something.
	if (hitParticles)
		hitParticles.emit = false;
	bulletsLeft = bulletsPerClip;
}

function LateUpdate() {
	if (muzzleFlash) {
		// We shot this frame, enable the muzzle flash
		if (m_LastFrameShot == Time.frameCount) {
			muzzleFlash.transform.localRotation = Quaternion.AngleAxis(Random.value * 360, Vector3.forward);
			muzzleFlash.enabled = true;

			if (audio) {
				if (!audio.isPlaying)
					audio.Play();
				audio.loop = true;
			}
		} else {
		// We didn't, disable the muzzle flash
			muzzleFlash.enabled = false;
			enabled = false;
			
			// Play sound
			if (audio)
			{
				audio.loop = false;
			}
		}
	}
}

function Fire () {
	if (bulletsLeft == 0)
		return;
	
	// If there is more than one bullet between the last and this frame
	// Reset the nextFireTime
	if (Time.time - fireRate > nextFireTime)
		nextFireTime = Time.time - Time.deltaTime;
	
	// Keep firing until we used up the fire time
	while( nextFireTime < Time.time  bulletsLeft != 0) {
		FireOneShot();
		nextFireTime += fireRate;
	}
}

function FireOneShot () {
	var direction = transform.TransformDirection(Vector3.forward);
	var hit : RaycastHit;
	
	// Did we hit anything?
	if (Physics.Raycast (transform.position, direction, hit, range)) {
		// Apply a force to the rigidbody we hit
		if (hit.rigidbody)
			hit.rigidbody.AddForceAtPosition(force * direction, hit.point);
		
		// Place the particle system for spawing out of place where we hit the surface!
		// And spawn a couple of particles
		if (hitParticles) {
			hitParticles.transform.position = hit.point;
			hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
			hitParticles.Emit();
		}

		// Send a damage message to the hit object			
		hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
	}
	
	bulletsLeft--;

	// Register that we shot this frame,
	// so that the LateUpdate function enabled the muzzleflash renderer for one frame
	m_LastFrameShot = Time.frameCount;
	enabled = true;
	
	// Reload gun in reload Time		
	if (bulletsLeft == 0)
		Reload();			
}

function Reload () {

	// Wait for reload time first - then add more bullets!
	yield WaitForSeconds(reloadTime);

	// We have a clip left reload
	if (clips > 0) {
		clips--;
		bulletsLeft = bulletsPerClip;
	}
	    if(Input.GetButtonUp("Reload")){
		clips--;
		bulletsLeft = bulletsPerClip;
    }
}


function GetBulletsLeft () {
	return bulletsLeft;
}

what is wrong? i can’t figure it out, i get no errors from it within unity, but it still doesn’t work

There doesn’t seem to be any code that detects the R key being pressed. However, it does seem as though it should reload automatically after a few seconds when the bullets are all used up. Is that not working either?

function Reload () {

   // Wait for reload time first - then add more bullets!
   yield WaitForSeconds(reloadTime);

   // We have a clip left reload
   if (clips > 0) {
      clips--;
      bulletsLeft = bulletsPerClip;
   }
       if(Input.GetButtonUp("Reload")){
      clips--;
      bulletsLeft = bulletsPerClip;
    }
}

thats the code the R button is set to reload, is it not setup right?

the auto reload is working, but i want it to be that you are also able to reload with out hitting 0 ammo left, and not automatically. (but still with the automatic reload when you hit 0)

I guess you must have set up an axis in the Input Manager for the reload key. Is it possible you’ve spelt “Reload” differently, say with a lowercase letter R in the inspector?

Nope it’s spelled right :frowning:

Hey there,
actually i never scripted in unity but i had a look at ur script and you tell to look if a button called Reload is pressed. dont you want that to be the actual “R” key.

im a newbie at scripting so its just an idea. maybe someone with more experience can help you with that

You can use names, rather than the keys themselves, so instead of W you can use Forward, which means that in the key config tab of the game launcher the user can set any key they like to = Forward or Reload.

If you do it using this method it gives more flexibility to the user who may not like your key setup, without it breaking your reload, walk, duck functions.

So can anyone help me with this problem?

I have tried putting the Getinput in the function update, but still didn’t work, that’s why im stumped on this :confused:

put this in your update function

//was the “R” key pressed?
if(Input.GetKey(“R”))
{
//call your reload function
Reload();
}

This still didn’t work :confused: Someone have this same problem?

Put your keypress check in a function Update(, so you would have:

function Update()
{
//was the "R" key pressed?
if(Input.GetKey("R"))
{
//call your reload function
Reload();
}
}

The reload function stays where it is, that way along with checking for your movement etc, (Which I assume you have in Update as well) it will check for the R keypress. You can’t call the function reload from within itself as it will only check for the keypress when the function is called and running.

i get this error every time

UnityException: Input Key named: R is unknown

sorry, use

KeyCode.R

not R

function Update()
{
//was the "R" key pressed?
if(Input.GetKey("KeyCode.R"))
{
//call your reload function
Reload();
}
}

so that’s it?

because that doesn’t work either

thanks for helping me through this[/quote]