- Home /
AddComponent with parameter variable
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?
Answer by Fire_Cube · Jul 06, 2016 at 12:26 PM
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 :)
ah, I was using GetType() and that was throwing up errors for me but typeof() is working fine.
Thank you.
Answer by Bunny83 · Jul 06, 2016 at 12:49 PM
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.