- Home /
Adding variables to a class at runtime
Hey guys, i'am making block editor for my game, the script is working in edit mode. I'am having a problem with adding variables for block creators when i choose a block type.
For example, when i choose "Gun" option the script should add new variables to class like "ShootingSpeed", and later the editor script should show it in the inspector. The problem lies in adding these variables, it seems that i'cant modify classes dynamicly or just add a new variables to class at runtime in C#.
[ExecuteInEditMode]
public class BlockCreator : MonoBehaviour
{
public enum Type // <---- This is a type enum, used for defining the type of the block and extending it's functionality
{
Hull,
Gun,
Engine,
Utility,
};
public enum Collidable
{
Yes,
No,
};
public int BX; //Volume variables
public int BY;//Volume variables
public float mass;
public int HP;//Hit points
public int Armor;
public Type BlockType;
public Collidable IsBlockCollidable;
void Update()
{
if (BlockType = Type.Gun) {
// Add Variables or do other things to add variables
}
}
public void CreateBlock()
{
//TODO generate a new prefab made with variables from BlockCreator Class
}
}
And the BlockCreatorEditor
[CustomEditor(typeof(BlockCreator))]
public class BlockCreatorEditor : Editor
{
public override void OnInspectorGUI ()
{
DrawDefaultInspector ();
BlockCreator myBlockCreator = (BlockCreator)target;
if(GUILayout.Button("Create Block"))
{
myBlockCreator.CreateBlock();
}
}
}
So in the end: Is there any way to add dynamicly variables at run time, and possibly how to do it? It would be the best to make it in C# but JavaScript can be used too.
I don't know of anyway to add a variable to a class at runtime. I would probably have made GUN a CO$$anonymous$$PONENT/mono-class with it's own variables defined at compile-time: you can always add/remove a component to a game object, when the block type is changed.
Only thing I've ever heard of but never used (sounds fancy though) is this:
https://msdn.microsoft.com/de-de/library/system.reflection.emit.typebuilder%28v=vs.110%29.aspx
Answer by MadoScien · Apr 14, 2015 at 04:42 PM
Thanks everybody for helpful comments. I've used Glurth method but slightly changed it. What i have done is that i have the types already written in program, so i'am "linking" them to the "block editor" and than oparates on whole object already. The editor is used only for linking and creating the prefab from the stuff that i wrote earlier.
Again thanks everybody for help!
Your answer
Follow this Question
Related Questions
how to link variable as inspector field 1 Answer
Custom Inspector - How to add functionality? 1 Answer
Parent Class variables in Child Class's Inspector (C#) 0 Answers
Instantiate a prefab vs create one dynamically at runtime? 1 Answer
Variable data type for two ints (x and y) in inspector 3 Answers