2

I'm currently working "with" Unity, mostly creating mods for a game that uses the Unity Engine. The "modloader" we use and I've worked on as well adds the mods to a GameObject. In order to do so, the mod needs to be derived from the class "MonoBehaviour". But I often forget to do so myself.

Is there a way to create an inheritance after compiling? For example with Reflection? Another thing I thought about was using Mono.Cecil and just setting the "BaseType" variable. Would that work?

I don't have any code, since it would require much work before that.

Thanks!

Letum
  • 223
  • 2
  • 6
  • 1
    Coding something like this is probably a lot more effort than a simple test run of the mod. Probably the better thing to do is to add the Stylecop add in to monodevelop and create custom rule that prevents you from compiling in the first place. – Ron Beyer Jul 25 '15 at 14:50
  • @RonBeyer the thing is that I'd like to implement it into the modloader. Therefor, I wanted to make something like a hook to the .AddComponent method, so if the class isn't derived from MonoBehaviour, it will be changed. Like "auto-inheriting". Anyway, thanks for the answer! I'll probably make a sample project and add Stylecop to it – Letum Jul 25 '15 at 15:52
  • 1
    You shouldn't try to fix code by writing utilities to fix it, fix it through testing, not patches. – Ron Beyer Jul 25 '15 at 16:12

1 Answers1

0

You are using orbital laser cannon to shoot fleas. Inherit from MonoBehaviour. That's it.

Unity's reflection is somewhat limited on certain platforms, certainly no code emission on iOS. I'd say it is a bad practice to venture too deep into Reflection-land unless there is no other way to accomplish what you want. Fortunately, it's not the case here.

You can do pre-compilation code modification: Compile-time source code modification using Roslyn

But, once again - just inherit from MonoBehaviour or create a class template - leave the orbital cannon alone.

pdeschain
  • 1,411
  • 12
  • 21