Simple question about button

Hi there.

I was trying to use C# as my first try on Unity. I just forgot it and begin to learn using javascript, because I couldn’t find proper docs and because I don’t know Unity well enought.

Anyway… I’m trying here to change a buttons text after user clicks it.
How can I do it?

My Code:

	if (new GUI.Button(Rect(10,10,150,30),"Turn Light 1 OFF"))
	{
		GameObject.Find("Light1").GetComponent(Light).enabled = true;
	}

I want to change its text to something like “Turn Light 1 ON”.

I’m very lost yet, please be patient :slight_smile:

Just did it.

Is that right? I MUST assign a variable to do this?

class LightList {
   var button_x : float = 10;
	var button_y : float = 10;
	var button_w : float = 150;
	var button_h : float = 30;
	var button_tOn : String = "Turn light OFF";
	var button_tOff : String = "Turn light ON";
	var objLight : GameObject;
}

var lightArray = new LightList[1];

function OnGUI () {
	for (var i : int = 0;i<lightArray.length;i++)
	{
		var _light : Light = lightArray[i].objLight.GetComponent(Light);
		var button_t : String = _light.enabled ? lightArray[i].button_tOn : lightArray[i].button_tOff;
		if (new GUI.Button(Rect(lightArray[i].button_x,lightArray[i].button_y,lightArray[i].button_w,lightArray[i].button_h),button_t))
		{
			
			_light.enabled = !_light.enabled;
		}
	}

}

For speed purpose, and smaller code, you may want to use :

var currentLightList : LightList;
currentLightList = lightArray [i];

and replace every lightArray by currentLightList.
currentLightList is …longer, so you may rename it as you want.
Anyway, the idea is good, well done.

I can hardly understand the code, but i think you may want light the button where the mouse is on, don’t you?.
Because if is that, you would prefer avoid read an array and try this (pseudocode)…

//1
if (buttonAux != null) buttonAux.enable = off
//2
buttonAux = currentLight
//3
buttonAux.enabled = true

The idea is to store the reference of current light into buttonAux; 1) at first it will be null and will skip the IF sentence, 2) but inmediately it will store the current light (still off).
After store the reference, 3) you will turn enabled buttonAux variable, and it will get turned on.

When you move the mouse over another button, the method will turn the light inside buttonAux off, and will continue the cylce from 2).

I hope you understood me

Just to note, GUI.Button is a function, not a class and so you don’t want the “new” keyword in front of it.