Hi guys.
I’m creating an RPG and I want to be able to add and remove Spells (Monobehaviours) from my character dynamically. So two functions on my Player script to add and remove Spells from the player’s GameObject. The problem is I want to pass the spell, name of the spell, whatever as a variable to these methods. So Explicitly I can say:
void AddSpell()
{
gameObject.AddComponent<Meteor>();
}
void RemoveSkill()
{
Destroy(GetComponent<Meteor>());
}
that’s fine. However I’m unsure how to pass my Meteor Monobehaviour (or any other Spell Monobehaviour) as a variable. I’ve done some reading and I figure I can’t use AddComponent<T>() with a variable because the Type has to be defined at compile time but I can use AddComponent() right? However I obviously can’t create a New instance of any Monobehaviours. I can’t use gameObject.AddComponent(Resources.Load("").GetType) because then it’s saying that GetType is a method group instead and I don’t know how to store Meteor as a type to send as a parameter.
Any ideas?
2 Answers
2
You can use the .GetType() or typeof(type) to get the type, and then pass it in parameter like this :
AddComponent(type);
It’s as simple as that 
Well, it depends on how you want to use your methods. There are many different ways.
First you could make your methods also generic methods.
public void AddSpell<T>() where T : MonoBehaviour
{
T inst = gameObject.AddComponent<T>();
}
If you have some sort of “Spell” base-class you might want to restrict the generic parameter to that base class instead of MonoBehaviour. Of course a generic class can only do “generic” things to the object based on the generic constraints.
You would use that method just like the AddComponent method:
player.AddSpell<Meteor>();
Second you could pass a System.Type reference:
public void AddSpell(System.Type aType)
{
Component inst = gameObject.AddComponent(aType);
}
This allows you to add any component class to your object. However, just like the generic version inside your method you can only access your component in a generic / abstract manner. If you always use a certain baseclass you can cast the “inst” reference to that base class.
This version could be used like this:
player.AddSpell(typeof(Meteor));
This version allows you to use a variable for the type
System.Type someVar = typeof(YourComponentClass);
player.AddSpell(someVar);
You did not give a concrete usecase so we can’t give a concrete example.
In my input section I turned engine force on and off and that would used to calculate the force. The switch would be, if ship is moving forward then pressing backwards/brake would switch engine force to negative 1 instead of 1. The way Ive got it set up is how I would do it.
– VAN-D00M