1

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.

Mario Hess
  • 159
  • 1
  • 12

1 Answers1

1

Instead of

Debug.Log(itemObject.item.atkBonus);

try

WeaponObject wo = (WeaponObject) itemObject.item;
Debug.Log(wo.atkBonus);
Daniel
  • 7,357
  • 7
  • 32
  • 84
  • 1
    Doesn't it create another instance of that ScriptableObject while the entire point of them was to reduce the amount of clones and be able to access it's properties from anywhere? So it's basically like a singleton object that I have to create another copy of whenever I wanna access it's properties? – Tengiz Jan 25 '22 at 11:55