Array of scripts on component
Hey!
I'm currently experimenting with Unity and I like it. However, I've encountered something that seems a bit odd to me.
I've got a base class; SpellBase which is abstract and only contains a Texture2d property and field. It also contains an abstract method "Execute".
I also got an UnitBase class which is not abstract. This class then has an array of Spell base. My idea was to populate this array of spell base with scripts to my prefabs. However, the array only accepts GameObjects in my scene.
Is there a way to allow scripts/components as part of another component?
I'd like to avoid having all my spells as "normal" components, the list would get so long from all spells I've been planning for play around with.
Thanks in advance Kevin
Answer by Injourn · Apr 18, 2016 at 07:56 PM
My best guess would be to make spells not inherit from MonoBehaviour and to make Spells serializable
[System.Serializable]
public class Spells //remove MonoBehaviour here
{
//cool stuff
}
$$anonymous$$y spell base already has the System.Serializable attribute. When I removed the $$anonymous$$onoBehaviour inheritance the array wouldn't render anymore in the Unity Editor.
class UnitBase : $$anonymous$$onoBehaviour
{
public bool Selected;
public int Health;
public float Armor;
public float PierceArmor;
public float Damage;
public DamageType DamageType;
public float $$anonymous$$ovementSpeed;
public SpellBase[] Spells;
....
}
[System.Serializable]
public abstract class SpellBase
{
public Texture2D _spellIcon;
public Texture2D SpellIcon
{
get { return _spellIcon; }
}
public abstract void Execute();
}
public class $$anonymous$$agicSpell : SpellBase
{
public override void Execute()
{
Debug.Log("Casting a magic spell!");
}
}
I've tried to add constructors to all of my classes but nothing helped.
Your answer
Follow this Question
Related Questions
Generic arrays? 1 Answer
Iterate through dialogue array and display in game 1 Answer
Storing a Gameobject from array into a Gameobject variable giving NullReferenceException 3 Answers
Fields not populated during OnValidate on Editor startup 2 Answers
Cannot convert UnityEngine.GameObject to UnityEngine.GameObject 1 Answer