- Home /
best method for high volume script management
Hi,
I am trying to make a POE/Diablo type game and am running into some logistical trouble. I am loading an active spell onto a button via gameobject. i need to get the component of the spell on that game object. there are a bunch of spells and i was hoping to not have to do this:
if(getComponent<FireBall>()){
Cast();
}
if(getComponent<RaiseDead>(){
Cast();
}
ect times way too many...
I was hoping i could pass a string as the component type, something like this...
public string componentName
spell.GetComponent <componentName>().Cast ();
i know the docs give an example...
HingeJoint hinge = GetComponent("HingeJoint") as HingeJoint;
but it requires the name of the component to be hard coded in for example this also would require way to many if statements.
FireBall activeSpell = GetComponent("componentName ") as FireBall ;
I'm stumped and i was wondering if anyone had any good ideas.
take a look at inheritance or interfaces - they could solve your problem.
Answer by pako · Sep 26, 2016 at 01:18 PM
It looks like that you should create an abstract "Spell" class, which will contain a virtual Cast() method.
Then each of your spells like FireBall and RaiseDead etc will inherit from Spell, and override Cast(), so that each particular spell implements Cast() in its own particular way.
Then you would do:
if(getComponent<Spell>()){
Cast();
}
or as applicable in your code, i.e. Spell.Cast() has to be called, and it would work for all types of spell, because they all inherit from the Spell class.
BTW, this is a brief description of the Strategy Design pattern, which is very useful in situations like this (Google it?).