- Home /
IF in a GUI
Hi Guys, how i put a IF in a text field for example:
GUI.Box (Rect(Screen.width * (guix),Screen.height * (guiy),Screen.width * (guiw), Screen.height * (guih)),
if(RifleShort > 0){ "Content" }
);
But, not work :/ Have other Way? I tryng to make for example,
if(RifleAmmo > 0){ " \n RifleAmmo : More than..." } if(PistolAmmo > 0){ "\n Pistol Ammo : More than..." } if(SubMachineGunAmmo > 0){ "\n Sub... Ammo : More than..." }
Answer by Bunny83 · Jan 03, 2012 at 12:18 AM
An if statement influence the control flow and represent a conditional branch in the execution order. It can't be used inside an atomic instruction as parameter.
If you want to pass a different string as parameter depending on a condition you have several possibilities:
- Use a variable as parameter which get set to the desired value before you call your GUI.Box:
var text = ""; if(RifleShort > 0) { text = "Content"; } GUI.Box (Rect(Screen.width * (guix),Screen.height * (guiy),Screen.width * (guiw), Screen.height * (guih)), text);
- direct call different versions:
if(RifleShort > 0) { GUI.Box (Rect(Screen.width * (guix),Screen.height * (guiy),Screen.width * (guiw), Screen.height * (guih)), "Content"); } else { GUI.Box (Rect(Screen.width * (guix),Screen.height * (guiy),Screen.width * (guiw), Screen.height * (guih)), ""); }
- or use the ternary operator (?) which takes a condition and two arguments:
GUI.Box (Rect(Screen.width * (guix),Screen.height * (guiy),Screen.width * (guiw), Screen.height * (guih)), ((RifleShort > 0)?"Content":""));
The ternary operator should be avoided since it results in very long lines and it's difficult to read.
Answer by Rod-Green · Jan 03, 2012 at 12:24 AM
Well.. the simple answer is to just assign it to a string and apply the assigned string..
var theString : string = "DEFAULT";
if(RifleShort > 0)
theString += "Conent";
Debug.Log(theString);
Then you can use that string however you want.. so..
var theRifleString : string = "";
if(RifleAmmo > 0)
{
theRifleString = " n RifleAmmo : More than...";
}
var thePistolString : string = "";
if(PistolAmmo > 0)
{
thePistolString = "n Pistol Ammo : More than...";
}
var theMachineGunString : string = "";
if(SubMachineGunAmmo > 0)
{
theMachineGunString = "n Sub... Ammo : More than...";
}
I guess the OP uses UnityScript since he doesn't have a "new" in front of "Rect". So just for the record, this example is written in C# ;)
Hah you're right. I tried to work it out from the sample code but I missed the 'new Rect' good catch.. Ill tweak my examples