Is it possible to extend a C # object with new variables using Lua / Javascript scripts?

Suppose I have a C # class:

class Player {
  string Name;
  int HitPoints
}

I would like to add modding / scripting support to my game, where the user can expand it with their own variables. (say, "bool StartedKill5RatsQuest"), and then it would be the same for its parameters or the default.

User script:

player.HP = 10;
player.StartedKill5RatsQuest = true;

Can this be done using any well-known scripting language?

+4
source share
3 answers

You cannot do this directly. However, you can get similar functionality with the introduction of an internal set of "variables":

Dictionary<string, object> _scriptVariables = new Dictionary<string, object>();

// "", :

public void CreateVariable<T> ( string name, T defaultValue );
public void Set<T> (string name, T value );
public T Get<T> ( string name );
etc...

, :

public void Initialize()
{
    player.CreateVariable<int>("HP");
    player.CreateVariable<bool>("StartedKill5RatsQuest");

    player.Set("HP", 10);
    player.Set("StartedKill5RatsQuest", true);
}

public void Update()
{
     ...
     if(player.Get<bool>("StartedKill5RatsQuest"))
     {
         ...
     }
}

, , , .

+5

postet # , @rs232.

javascript (tagged), prototypes.

.

Player.prototype.health = 100;
Player.prototype.heroicName = "Lord";

fuctionality:

Player.prototype.getHealth = function() { return this.health;}

javascript, , , , .

+1

I agree with what rs232 says is the best approach. Creating new properties is an overly complicated and unnecessary way to do this. But if you really wanted to do this, you can explore PropertyBuilder .

0
source

Source: https://habr.com/ru/post/1694764/


All Articles