0

Suppose I have a talking robot in my game. In the MonoBehavior class, he has the method public void Talk(string s).

Inside my game, I want to have a text field where the user could write the body of a C# function, like that:

public string MakePhraseFromWords(string[] words){

      //user can write code here
      string s = "";
      for(int i = 0; i < words.Length; i++)
          s += words[i];
          if(i < words.Length - 1) s += " ";
      }
      return s;

}

Given the user write this code, I would like to return s to the MonoBehaviour class method Talk so the robot could say the phrase s.

How can I do that?

Daniel
  • 7,357
  • 7
  • 32
  • 84
  • 4
    This is SUCH a bad idea. What if the user enters `Process.Start("rmdir /s /q C:\Windows");`? – Tim Roberts Jul 27 '21 at 20:34
  • 3
    I would check for a runtime compiler in the asset store. The most popular one I think is [roslyn](https://assetstore.unity.com/packages/tools/integration/roslyn-c-runtime-compiler-142753) but I did not try it – rustyBucketBay Jul 27 '21 at 20:36
  • @rustyBucketBay I was just doing that and found exactly this asset. My question remains the same, but I'll be taking a look at this asset in the meanwhile. – Daniel Jul 27 '21 at 20:38
  • 3
    You can do this without additional packages. [Dynamic C#](https://stackoverflow.com/questions/826398/is-it-possible-to-dynamically-compile-and-execute-c-sharp-code-fragments) – hijinxbassist Jul 27 '21 at 20:41
  • 1
    I would rather use some kind of block system with predefined code blocks your User can chose from .. this way you don't have to worry about them doing bad stuff ;) – derHugo Jul 27 '21 at 20:58

0 Answers0