Unity跨脚本调用方法报错:无法通过实例引用访问ListItems()
Unity调用Inventory.ListItems()报错解决方法
错误提示:
member InventoryManager.ListItems() cannot be accessed with an instance reference; qualify it with a type name instead
你没有把ListItems()设为静态,但报错的根源不在这个方法,而是调用GetComponent的方式有误。
你的代码片段
InventoryManager中的ListItems方法:
public void ListItems() { foreach(var item in Items) { GameObject obj = Instantiate(InventoryItem, ItemContent); var itemName = obj.transform.Find("Item/ItemName").GetComponent<Text>(); var itemIcon = obj.transform.Find("Item/ItemIcon").GetComponent<Image>(); itemName.text = item.itemName; itemIcon.sprite = item.icon; } }
另一个类的Update方法:
public GameObject inventory; public InventoryManager i; public void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { InventoryManager.GetComponent<InventoryManager>().ListItems(); inventory.gameObject.SetActive(!inventory.gameObject.activeSelf); } }
错误原因
GetComponent<T>()是实例方法,必须通过具体的GameObject实例调用,你直接用类名InventoryManager调用,相当于把它当成静态方法使用,这才触发了报错。
修复方案
方案1:使用已声明的InventoryManager实例
如果你已经在Inspector面板给变量i赋值了对应的InventoryManager组件实例,直接用这个实例调用方法:
public GameObject inventory; public InventoryManager i; void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { i.ListItems(); inventory.SetActive(!inventory.activeSelf); // 冗余的.gameObject可以去掉 } }
方案2:从背包对象上获取组件
如果不想提前赋值,直接从背包UI对象(inventory)上获取InventoryManager组件:
public GameObject inventory; void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { var inventoryManager = inventory.GetComponent<InventoryManager>(); inventoryManager.ListItems(); inventory.SetActive(!inventory.activeSelf); } }
注意事项
- 确保InventoryManager脚本确实挂载在对应的GameObject上(要么是赋值给
i的对象,要么是inventory对象) - 调用SetActive时,
inventory本身就是GameObject类型,无需再加.gameObject
内容的提问来源于stack exchange,提问作者Potato
相关产品推荐
相关产品推荐

