Constructing from ScriptableObject?

I have a derived class SpeedBoostEffect, which derives from StatusEffect.

abstract public class StatusEffect : ScriptableObject
{
    //Codes here
}

public class SpeedBoostEffect : StatusEffect
{
    //Codes here
}

I create a .asset based on SpeedBoostEffect, and I attached the configuration of the .asset file to triggeredTrap.cs

public class triggeredTrap : MonoBehaviour
{
    public StatusEffect triggeredEffect;
 
    void OnTriggerEnter(Collider other)
    {
        CharacterStats pStats= other.GetComponent<CharacterStats>();
        if (pStats && triggeredEffect != null)
        {
            //SpeedBoostEffect eff = new SpeedBoostEffect();
            //pStats.AddStatusEffect(eff); //This works
            pStats.AddStatusEffect(triggeredEffect); //This works, but I want a new instance of the derived class instead of the ScriptableObject.asset reference.
           //pStats.AddStatusEffect(new triggeredEffect.Construct()) //Ideally something like this!
        }
    }
}

Creating new SpeedBoostEffect works, but I am creating a lot of derived class. Such as AttackBoostEffect, so I can’t have a defined type.
In this case, what is the right way to do this?

Thank you.

Tried this.

pStats.AddStatusEffect((StatusEffect)ScriptableObject.CreateInstance(triggeredEffect.GetType()));

Also does not work…

Also tried this

abstract public class StatusEffect : ScriptableObject
{
    public virtual StatusEffect ConstructNewStatusEffect()
    {
        return Activator.CreateInstance(this.GetType()) as StatusEffect;
    }
}

pStats.AddStatusEffect(triggeredEffect.ConstructNewStatusEffect());

Gave this error.

Found a solution!

public virtual StatusEffect CreateStatusEffectInstance()
{
    return ScriptableObject.CreateInstance(this.GetType()) as StatusEffect;
}

And calling it in the triggered trap ended up working.

pStats.AddStatusEffect(triggeredEffect.CreateStatusEffectInstance());

Solved.

1 Like