- Home /
Question by
thealexguy1 · Aug 09, 2017 at 07:17 AM ·
stringvoidsimplify
How to convert a 'string' to the name of a 'void' function?
Hi there, I was just wondering if there was any way I could simplify my below code here: (instead of having to keep duplicating the code every time I make a new sign) I was thinking the way to do it would be to convert the variable 'signTouchingName' into the name of the void function I am calling.
if (signTouching.name == "Sign1") {
GameObject.Find ("MessageBox").GetComponent<MessageText> ().Sign1 ();
} else if (signTouching.name == "Sign2") {
GameObject.Find ("MessageBox").GetComponent<MessageText> ().Sign2 ();
} else if (signTouching.name == "Sign3") {
GameObject.Find ("MessageBox").GetComponent<MessageText> ().Sign3 ();
} else if (signTouching.name == "Sign4") {
GameObject.Find ("MessageBox").GetComponent<MessageText> ().Sign4 ();
} else if (signTouching.name == "Sign5") {
GameObject.Find ("MessageBox").GetComponent<MessageText> ().Sign5 ();
}
Any help appreciated thank you
Comment
Best Answer
Answer by ShadyProductions · Aug 09, 2017 at 07:24 AM
Why not make 1 function where you can pass an int
public void Sign(int number) {
}
that would make it easier, you could do something like this:
// Substring(4) only takes all characters after the first 4
// Then I parse the character that we receive from string to an int
var number = int.Parse(signTouching.name.Substring(4));
.Sign(number);