- Home /
Executing a string as a code snippet.
This question has been asked numerous of times, but I still haven't found a working solution on this. I have several sprites that act as buttons (the UI buttons are unusable in this scenario). The button needs to execute a function on a different script. Now, I want to make a public string
so that I can input the function name in the editor for every single button, so that every button calls a different function.
Is there a way to somehow convert a string to an executable piece of code, so that it can be run in a script both in the Editor and at Runtime?
I know this can be done in JS using eval()
but I am using C#, so that won't work.
In your case you can use Send$$anonymous$$essage
but this is a terrible solution.
Can't you use Unity events?
https://forum.unity.com/threads/unityevent-where-have-you-been-all-my-life.321103/
I've never heard about Unity Events! I'll check it out!
Answer by Lapraniteon · May 01, 2020 at 09:51 AM
This is what Hellium said in his comment:
In your case you can use SendMessage but this is a terrible solution.
Can't you use Unity events?
https://forum.unity.com/threads/unityevent-where-have-you-been-all-my-life.321103/
This is the correct answer.
Answer by Cassos · May 01, 2020 at 10:16 AM
Just use Invoke("string"). That works fine
Why you devote this? That works perfectly fine.
You could use UnityEvents too
Very uncool to devote somebody who just wants to help with something that works
Invoke
can be great for prototyping, but is a nightmare for code maintability because you pass the name of the function as a string.
You can't refactor the name of the function without doing a
Find & Replace
in your IDEThe stacktrace is a nightmare to follow when a function has been called by the
Invoke
methodYou can't pass arguments with to the method called by
Invoke
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Does unity C# support an exec method? 1 Answer
Multiple Cars not working 1 Answer
How to count the number of strings in a string class? 2 Answers
Most efficient way to convert string[] to int [] in C#? 2 Answers