简体   繁体   中英

how do i get the values stored inside a gameobject from a script?

public class inventorySlots : MonoBehaviour, IDropHandler
{
   void Start()
   {
      if(transform.childCount != 0)
      {
         GameObject itemInSlot = transform.GetChild(0).gameObject;
         item item = itemInSlot.GetComponent<item>();
         Debug.Log(item.Slot);
      }
   }
}
public class item : ScriptableObject
{
    public Slot Slot;
    public int id;
    ...
}
public enum Slot
{
    equippableInHelmet;
    equippableInChestplate;
    ...
}

I am trying to get the Slot enum from the class item from the script, it compiles on unity but it doesen't print the slot enum, this is the error i receive:

ArgumentException: GetComponent requires that the requested component 'item' derives from MonoBehaviour or Component or is an interface.

All the class properties are public, i have tried with the id also but id doesn't work.

In Unity, the GetComponent<> method can only fetch a class deriving from the MonoBehaviour or Component class. In this case, the item class does not derive from MonoBehaviour , instead, it derives from ScriptableObject .

How to fix

There are two ways that would work to fix this problem.

The first way that you can fix this is by changing the class in which the item class derives from to MonoBehaviour , instead of ScriptableObject .

The second, more complicated way to fix this problem is to create a variable to hold the ScriptableObject , instead of fetching it with GetComponent<> . The code would look something like this:

...

public item item;

void Start()
{
   Debug.Log(item.Slot);
}

...

You should then assign the item variable in the inspector.

If you want to learn more about ScriptableObject , this video is extremely helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM