Greygraphics
Greygraphics

Reputation: 3

C# Redirecting Method calls from other Projects to own Methods - How?

I am using Unity and want users to be able to create own programs that will be executed in the running project.

I want to create some kind of API that does the work within the project (like spawning an entity)

class Foo
{
 void SpawnEntity()
 {
  //Code to spawn entity
 }
}

Users should be able to submit their own code as .dll files with one method that will be executed

class Userclass
{
 void MyCode()
 {
  //Their code would have to use some kind of API to do something in the game
  Foo.SpawnEntity();
 }
}

I thought about having something like

namespace APIS
{
 class Foo
 {
  void SpawnEntity()
  {
   //This method does not contain actual code
  }
 }
}

in the user submitted .dll file, which would result in

class Userclass
{
 void MyCode()
 {
  //Their code would have to use some kind of API to do something in the game
  APIS.Foo.SpawnEntity();
 }
}

My question is if I could overwrite the method APIS.Foo.SpawnEntity() with one that is already compiled in the code of the game like

namespace UnityEngine
{
 class Foo
 {
  void SpawnEntity()
  {
   //The actual code that does something in the game
  }
 }
}

So far I only found examples of calling methods in external .dll files and getting their return value, but no examples of actually overwriting methods in those .dll files to change things in the calling program (the Unity game in this case).

Is this even possible with C#?

Thank you in advance

Edit: Probably impossible in C#, using scripting language

Upvotes: 0

Views: 69

Answers (1)

Adam
Adam

Reputation: 33126

Standard approach: embed a scripting language.

There are multiple plugins available that provide this already for unity, in various languages from Lua to JS, even C# (although C# is tricky, because Apple has banned this kind of scriptng on iOS).

An external scripting language has several major benefits:

  1. Your audience may not know the language you're using (C#); you can give them multiple options
  2. They will only have access to the classes and methods you explicitly pass to the Scripting Language subsystem; this greatly reduces the chances of them messing up, and makes it easier for them (they have fewer API docs to read, etc)
  3. If the scripting-system crashes, you can keep the game running, even reset the scripting system atuomatically while the game runs.
  4. You can give the user performance info on their scripts, by measuring the scripting system from frame to frame.

Upvotes: 1

Related Questions