Stored color variable resetting itself to black after exiting function.

Hey all,

I have the following code for changing the color of objects:

function WasTouched(){
		if (gemSelected==false){
		gemSelected=true;
		var thisGemColor : Color = renderer.material.GetColor("_Color");
		Debug.Log(thisGemColor);
		renderer.material.color=Color.white;
	}
	else  {
		gemSelected=false;
		Debug.Log(thisGemColor);
		renderer.material.SetColor("_Color",thisGemColor);
	}

If the original color of my object was green, when I select it a 2nd time, it’s black RGBA(0,0,0,0) instead of returning to green. I’m assuming because the variable is inside the WasTouched() function and upon exit, is forgotten about. (probably due to poor code)

Can I get around this some other way? Maybe storing the variable outside all functions with GetComponent() ?

You variable is local to the if statement. renderer.material.GetColor(“_Color”) can be shortened the same way SetColor can. I don’t think your function is named well, but can’t recommend a better name without knowing more about how it would be used. A function with the name “Was…” sounds like it should be returning a bool, to me.

var thisGemColor : Color;
function WasTouched () {
	if (gemSelected) renderer.material.color = thisGemColor;
	else {
		thisGemColor = renderer.material.color;
		renderer.material.color = Color.white;
	}
	Debug.Log(thisGemColor);
	gemSelected = !gemselected;
}

The function is called using a SendMessage() function by my touch detection script. So the touch controls tell a gem that it “WasTouched”. At least that’s how I see it in my head.

The logic is:

  • if it’s touched, make sure gemSelected is true
  • Record the original color of this gem
  • set the new color to white (just field testing selection)
    -if gemSelected is already true, set it to false (deselect)
  • return the gem to it’s original color.

so I can simply define var thisGemColor : Color; outside the function and i’ll be set? (I’d test, but I don’t have my development gear in front of me).

Yes, you need to variable’s scope to be in the class, not in the function.

I don’t understand the logic for your code. I’d probably be updating a raycast every frame that a finger was down.

FYI this is resolved. I apologize for the late update.

Declaring the scope of my variable outside of that function gave me the desired behavior.

I appreciate your help Jessy. :slight_smile: