GUI.Button datatype

Hi all,

Just getting into unity. I’m learning how to do buttons. :slight_smile:

The normal way to create a button seems to be:

if (GUI.Button(Rect(10,10,50,50), “Click me”)){
// do somthing
}

This seems wierd to me, creating an instance inside a if function. I would do this:

var b = GUI.Button(Rect(10,10,50,50), “Click me”));
if (b){
// do somthing
}

  1. That works, but would it be bad practice?
  2. When putting a button into a variable, I would like to datatype it. What do you datatype a button with?

Jakob

The normal way is also a practical coding style. The GUI.Button is a method returning a boolean value to you. So consider below code as java, you can write

// some code
if (checkIfIAmDeveloper ()) {
System.out.println("Indeed you are!");
}
else {
System.out.println("No, sir, not even close :)");
}

public boolean checkIfIAmDeveloper ()
{
// logic to check if I am a developer
}

Your style practically makes no difference for UnityScript, because of the dynamic type casting feature. However, you should know the data type for mobile platforms and for C#, which is a boolean value.

There is no dynamic typing involved, it works without issues on mobile platforms, and “var b = GUI.Button(new Rect(10,10,50,50), “Click me”);” is perfectly valid C#.

It’s just calling a function that returns a boolean, which is an extremely common thing to do.

if (GUI.Button(Rect(10,10,50,50), "Click me"))
if (Input.GetKeyDown(KeyCode.A))
if (Physics.Raycast(transform.position, transform.forward, 100.0))

Your method creates another variable but otherwise works the same; whether that’s good practice depends on whether it makes it easier for you to understand. As for what type things are, the docs always tell you that.

–Eric

Yes, I know it is perfectly valid for c#.
I have confused some things about #pragma strict, thanks for clarification.

Yepp.