简体   繁体   中英

How to compile and run C# code at runtime where the compiled code can access the rest of the program

I have a C# game, I wish to allow our scripter to write small code files such as what is below so we can patch and mod some of our systems.

namespace Game.Creatures
{
    public class Zombie : Creature
    {
        public override float MovementRange { get { return 12; } }
        public override float AttackDamage { get { return 5; } }
        public override float TurnSpeed { get { return 2; } }
        public override float WalkSpeed { get { return 1.7f; } }
        public override float RunSpeed { get { return 2.5f; } }
        public override float TimeBetweenAttacksSeconds { get { return 0; } }
        public override bool CanAttack { get { return false; } }

        public Zombie(Vector3 in_Position, Vector3 in_Scale)
        {
            Health = MaxHealth = 40;
            CurrentAi = new Ai_Simple(this) {RecalcPathIn = -1};
        }

        public override void Update(GameTime in_GameTime) { base.Update(in_GameTime); }
        public override void Render(GameTime in_GameTime) { base.Render(in_GameTime); }
    }
}

As you can see the file uses types and methods from the game, is this possible or does any runtime created code need to be confined to itself?

Bonus if it also works on the 360.

Edit: Paint.net has a code lab plugin that does exactly this, so I know it must be possible.

Is it possible to dynamically compile and execute C# code fragments? deals with the same thing. Being able to reference your classes just means that one of the assemblies you want to reference should be the one with Creature in it. Eg

var parameters = new CompilerParameters(
 new[] { "mscorlib.dll", "System.Core.dll", "MyAssembly.dll" }, "foo.exe", true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM