- Home /
if statement help!
Hi there!
Please excuse the title of this thread, I really didn't know what to call it!
Anyway:
I have a timer ticking in seconds that decrease a variable called "thirst". When "thirst" reaches a certain number, it will display on the GUI however this only works for the numbers it's given.
if(thirst == 100){
GUI.Label (Rect(40, Screen.height - 70,60,60)," Hydrated", style2);
}
if(thirst == 80){
GUI.Label (Rect(40, Screen.height - 70,60,60)," Dry", style3);
}
if(thirst == 60){
GUI.Label (Rect(40, Screen.height - 70,60,60)," Thristy", style4);
}
if(thirst == 40){
GUI.Label (Rect(40, Screen.height - 70,60,60)," Dehydrated", style5);
}
if(thirst == 20){
GUI.Label (Rect(40, Screen.height - 70,60,60)," Parched", style6);
}
if(thirst == 10){
GUI.Label (Rect(40, Screen.height - 70,60,60)," Dying", style7);
}
It's only showing for when the variable hits 100,80,60,40,20,10 - how can i make it show for 99,98,97 all the way down to 0 without having 100 if statements?
I hope this is clear, Thanks in advance!
Answer by hathol · Aug 12, 2012 at 11:46 PM
Ok, first thing: there is a thing called "else" or "else if" respectively. Syntax is
if(A)
{
// do something if A is true
}
else if(B)
{
// do something if A is not true and B is true
}
else
{
// do something if neither A or B are true
}
you also have the <= (less than or equal) and >= (greater or equal) operators (checks for exactly that) Now with that in mind, you could write
if(thirst <= 10)
{
//for 0 - 10
}
else if(thirst <= 20)
{
// for 11 to 20 since 0-10 has already been excluded
}
else if(thirst <= 30)
{
// 21 to 30
}
. // you get the point
. // I skiped 31 to 80 cause I'm lazy ;)
.
else if(thirst <= 90)
{
// 81 to 90
}
else
{
// 91 and above
}
Answer by Loius · Aug 12, 2012 at 11:39 PM
<=
or
var states : String[] = ["Dying", "Parched", "Parched", "Dehydrated", "Dehydrated", "Thristy", "Thristy", "Dry", "Dry", "Hydrated", "Hydrated"];
var styles : {type of styles}[]; // fill in in Inspector, could do this for states too
...
var thirstIndex : int = thirst * 0.1; // will convert thirst from 0-100 to 0-10
GUI.Label( {xxxx}, states[ thirstIndex ], styles[ thirstIndex ] );
Gotta love arrays.
Sometimes I think my brain's been replaced by a robot, but then I forget how to type and I'm reasonably sure it's still in its place.
Your answer
![](https://koobas.hobune.stream/wayback/20220613075553im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to make several conditions for an if statement? 5 Answers
if else statement doesnt work 1 Answer
Need help with multiple if statements. 3 Answers
if moving statement 1 Answer
Can I Put a IF In a IF?!? 2 Answers