How do I get two variables to switch places?

So I am working on my gun switch script, and I got it to work, except for one thing which causes it to only work once, and causes problems if you want to replace a gun. The problem that I am having is that I cannot get these two variables to switch. The variables are currentGun and secondaryGun. The commented out code causes problems in which the switching does not work correctly. Help!

if(Input.GetButtonDown("Switch Guns"))
		if(walkScript.currentGun == gameObject)
			Debug.Log("Pressed Q");
			walkScript.currentGun.GetComponent(GunScript).carrying = true;
			walkScript.currentGun.GetComponent(GunScript).isHeld = false;
			walkScript.secondaryGun.GetComponent(GunScript).carrying = false;
			walkScript.secondaryGun.GetComponent(GunScript).isHeld = true;
			//walkScript.currentGun = walkScript.secondaryGun;
			//walkScript.secondaryGun = gameObject;

You are going to have to create a temp variable like this:

var tempVar = currentGun; //saves current gun to a temp var so its isn't overwritten
currentGun = secondaryGun;
secondaryGun = tempVar;

If both guns have this script attached, then chances are highly likely that when you press Q, both of them are firing off the switch script. So, one instance of the gun script will swap the two, but then the other instance swaps it back!

I don’t suggest that have the gun switching code in the guns themselves. It’s bad design, and as you can see already, it’s gonna cause you trouble. Instead, take this script, modify it, and attach it to your character instead. The character is acting on the guns to switch them; I mean, would you find it weird in the real world if the guns switched themselves?

If you create a “Gun Switch” script that’s attached to the player, you can then place currentGun and secondaryGun in it instead of the walk script, which, should only be for walking.

Additionally, I see you have two separate variables for “carrying” and “held”. Instead, you could probably improve that by using only one variable. See, you can’t hold something and carry it at the same time, so simply treat isHeld = true as being held, and isHeld = false as being carried.

This works perfectly if you are not adding any other states. If you do intend to add other states, try making an enumuration:

public static var GunStatus
    "isHeld" : 0,
    "carrying" : 1,
    "dropped" : 2

Then, instead of isHeld and carrying variables, replace the two with one Number var called status, which can then be used like this:

// don't use #pragma strict for this to work
currentGun.status = GunStatus.isHeld;
secondaryGun.status = GunStatus.carrying;

Lastly, in order to swap the variables, you just need to create a temporary one:

var swapGun = currentGun;
currentGun = secondaryGun;
secondaryGun = swapGun;

Hope that helps!