Removing If-statements
Hello!
I'm building a 2D survival city builder. As a player you make characters gather resources and make tools or build buildings. These activities take a certain amount of time. I have multiple playable characters which can do multiple activities. A simplified example of the code for a activity is as follows:
public void SearchRocksClicked(){
if(charselected =="harry"){
harryactivityendtime = TotalMinuteAmount + Activitylength;
}}
Then I wrote a if-statement in the void update for what happens when the timer meets the end time:
void Update (){
if(TotalMinuteAmount == harryactivityendtime){
harryactivityendtime = 0;
harryrocks = harryrocks + 1;
}
Now I want more characters to do the same activity, but I would like to have only one 'OnClicked function'. Is there a way a function searches which person is selected, so it wil know to which Integers to write to, without having to make a if statement for every character?
Maybe I want to make the game too simple but every help is welcome. Thank you in advance!
Answer by hacvanbeek · Feb 14 at 09:53 PM
Hi Rob! Thanks for your answer. I could use coroutines for the activities to get rid of the if statements in the void update. But I would also like a solution for the rest of the if statements. Simplified, this is what I have now:
public void SearchRocks(){
if(charselected =="harry"){
harryrocks = harryrocks + 1;}
if(charselected =="john") {
johnrocks = johnrocks +1;}
if(charselected == "bob"){
bobrocks = bobrocks +1;}
// and so 50 more....
}
This way, if i have 100 characters, I have to add 100 if-statements for every activity. I was hoping it could be done in less lines. It would make adjusting the activities easier. Something like:
public void SearchRocks(){
if(charselected =="variable"){
variablerocks= variablerocks +1;
}
or maybe through referencing different scripts:
if(charselected =="variable"){
variable.rocks= variable.rocks +1;
}
I have been looking into storing a reference like this but I have not found the right method. Can you help me with this?
Your answer
Follow this Question
Related Questions
Button OnClick function? 1 Answer
Mobile Buttons not working? 0 Answers
How to combine a if statement with whether or not a certain button was clicked? 1 Answer
Im trying to make gameObject move only if specific button is pressed 1 Answer
Cursor Lock Code w/ if, else if, and else Statement Errors 1 Answer