Unity脚本获取GameObject内ScriptableObject数据报错求助
问题解决:Unity中无法获取ScriptableObject类型的item实例
错误原因
你遇到的ArgumentException是因为GetComponent<T>()只能获取继承自MonoBehaviour/Component的组件,或者接口类型。而你的item类继承自ScriptableObject,不属于这两类,所以用GetComponent<item>()根本拿不到实例,自然无法访问Slot和id属性。
解决方案
ScriptableObject是资源类,不能直接作为组件挂载到GameObject上,必须通过一个MonoBehaviour组件来持有它的引用。
步骤1:创建持有ScriptableObject的组件
新建一个继承自MonoBehaviour的脚本,用来存你的item实例:
public class ItemHolder : MonoBehaviour { public item Item; // 在Inspector面板拖入你的ScriptableObject物品实例 }
步骤2:修改inventorySlots的代码
不再直接获取item,而是先获取上面的ItemHolder组件,再从中拿到item实例:
public class inventorySlots : MonoBehaviour, IDropHandler { void Start() { if(transform.childCount != 0) { GameObject itemInSlot = transform.GetChild(0).gameObject; // 获取ItemHolder组件 ItemHolder itemHolder = itemInSlot.GetComponent<ItemHolder>(); if(itemHolder != null && itemHolder.Item != null) { // 现在可以正常访问属性了 Debug.Log(itemHolder.Item.Slot); Debug.Log(itemHolder.Item.id); } else { Debug.LogWarning("物品对象上没有挂载ItemHolder,或者未设置Item引用"); } } } }
额外修正:枚举语法错误
你的Slot枚举里用了分号分隔值,这是错误的,应该改成逗号:
public enum Slot { equippableInHelmet, equippableInChestplate, // ...其他枚举值 }
内容的提问来源于stack exchange,提问作者asaki
相关产品推荐
相关产品推荐

