- Home /
call function with same name + number
So I have 30 different functions all like this
public void level23()
{
theGame.levelSelected = 23;
}
This is what is called to setup the next level in game. I was wondering if there was a way for me to call this in a retry button by using something like this with theGame.levelSelected being an int
level + theGame.levelSelected();
this would save a rather long switch.
Answer by allenallenallen · Aug 05, 2015 at 08:33 AM
Well, first of all, you shouldn't have 30 different functions to change a single integer. Why not literally just change the integer?
Can you not type this every time you need to load a new level?
theGame.levelSelected = 23;
And if anything, you can do this:
public void LevelThing(int num){
theGame.levelSelected = num;
// Then do other things here if you want to.
}
there is a lot more that goes into that level function i just gave the basic code thats needed for this solution. It sets all the variables on the enemies as well as the goals etc. for the level
And all of that can be handled in the same long void, you know?
Look at this; https://unity3d.com/learn/tutorials/modules/beginner/scripting/switch
public void LevelThing(int num){
theGame.levelSelected = num;
switch (num){
case 1:
// Do all your level 1 specific set ups here.
break;
case 2:
// Do all your level 2 stuff here
break;
// And so on.
}
}
how would you go about setting theGame.levelSelected when you click on the level, as currently when you click on a level it runs the appropriate function
I'm guessing you didn't instantiate the buttons. If you did that you can just assign the number from an array to each of them.
If you can't instantiate the buttons for some reason, you can attach a script to each button and give itself an integer.
To answer the question directly (although I agree with allenallenallen that there seem to be ways to make it a lot more efficient): You can use Send$$anonymous$$essage to call a function by it's name as a string. This string can of course be whatever you like, such as "Your$$anonymous$$ethodName" + 23.ToString().
Your answer
Follow this Question
Related Questions
List.add() not working when function called by 2nd script 1 Answer
How can I call a method from another script? 3 Answers
Why is calling a function wrong? 2 Answers
Check if a function is no longer being called? 3 Answers
Multiple Cars not working 1 Answer