Swapping Objects (466847)

I have two objects, Orange and Blue.

Using the scripts below, they are supposed to switch(Blue becomes Orange, Orange becomes Blue)

However, this only occurs on the first swap…

//Make Blue into Orange
function Update () {

	if (Input.GetAxis("Space"))
		{
			GameObject.Instantiate(GameObject.Find("Orange"), transform.position, transform.rotation);
			Destroy(this.gameObject);
		}

}
//Make Orange into Blue
function Update () {

	if (Input.GetAxis("Space"))
		{
			GameObject.Instantiate(GameObject.Find("Blue"), transform.position, transform.rotation);
			Destroy(this.gameObject);
		}

}

well, my guess is that each time you hit space, you are creating two new objects. On blue, one orange. Then when you do it again… why would it change? you are just putting another blue, where blue goes, and orange where orange is.

I would do somthing like…

var blue : gameobject;
var orange : gameobject
var pos1 : vector3;
var pos2 : vector3;
var state : int;
function Start()
{
pos1 = blue.transform.position;
pos2 = orange.transform.position;
state = 1;
}


function Update () {
    if (Input.GetAxis("Space"))
{
if(state == 1){
blue.transform.position = pos1;
orange.transform.position = pos2;
state = 2;
}
if(state == 1){
blue.transform.position = pos2;
orange.transform.position = pos1;
state = 1;
}
}

this way, you always swap and you dont have to create a new object continually. It is less stressful to the engine.

This not only didn’t work, but it created more problems…

I think renman meant this:

var blue :GameObject;
var orange : GameObject;
var pos1 : Vector3;
var pos2 : Vector3;
var state : int;
function Start() {
pos1 = blue.transform.position;
pos2 = orange.transform.position;
state = 1;
}

function Update () {
    if (Input.GetAxis("Space"))
    {
        if(state == 1) {
            blue.transform.position = pos1;
            orange.transform.position = pos2;
            state = 2;
        }
        if(state == 2) {
            blue.transform.position = pos2;
            orange.transform.position = pos1;
            state = 1;
        }
}

Attach a script with that code to an object in the scene, it doesn’t matter which one, and be sure to assign blue and orange in the Inspector window.

That should work. If it doesn’t, could you please post exactly what errors you’re getting here?

This worked the same as mine, but not for my needs. The reason I have it destroying and instantiating a new object is because there are more than one “Blue” and “Orange” in the room, therefore just moving the objects won’t work.

[EDIT] I fixed the problem with not toggling on more than the first time by changing the second ‘if’ to an ‘else’ statement. Now I just have to try combining my code with yours. Thanks!

Is this C sharp or js ?