Mario Hess
Mario Hess

Reputation: 167

ScriptableObject abstract class: access child variable

I am trying to create an item system for my game, but I can't access different variables in my Sriptable Objects that inherit from the same abstract class.

I've got an abstract class that derives from SriptableObject:

//ItemObject
public abstract class ItemObject : ScriptableObject
{
    public GameObject prefab;
    public ItemType type;
    public string itemName;
    [TextArea(15,10)]
    public string description;
}

//ItemType
    public enum ItemType
    {
        Potion,
        Weapon,
        Default
    }

I create an ItemController which sits on a GameObject:

//ItemController
public class ItemController : MonoBehaviour
{
    public ItemObject item;
}

I create a Scriptable Object that derives from ItemObject, and i hook the created Scriptable Object onto the ItemController Script:

//WeaponObject
[CreateAssetMenu(fileName = "New Weapon Object", menuName = "Inventory System/Items/Weapon")]
public class WeaponObject : ItemObject
{
    public float atkBonus;
    public float defBonus;
    
    private void Awake()
    {
        type = ItemType.Weapon;
    }
}

I'm trying to perform a Raycast to the Object on which the ItemController sits, and I'm trying to access the atkBonus variable from my WeaponObject.

//PlayerController
 private void Update()
    {
        RaycastHit hit;
        if (Physics.Raycast(this.transform.position, this.transform.forward, out hit, 2f))
        {
            var itemObject = hit.transform.GetComponent<ItemController>();
            if(itemObject)
            {
                Debug.Log(itemObject.item.atkBonus);
            }    
        } 
    }

This throws me an error and I can't figure out why. "error: 'ItemObject' does not contain a definition for 'atkBonus' and no accessible extension method 'atkBonus'..."

I can access the variables from the parent abstract class tho.

Debug.Log(itemObject.item.itemName);

Does anybody know how to solve this?

Thank you.

Upvotes: 1

Views: 2112

Answers (1)

Daniel
Daniel

Reputation: 7724

Instead of

Debug.Log(itemObject.item.atkBonus);

try

WeaponObject wo = (WeaponObject) itemObject.item;
Debug.Log(wo.atkBonus);

Upvotes: 1

Related Questions