Unity C# Problems

本文关键字:Problems Unity | 更新日期: 2023-09-27 18:28:30

我收到这个错误:

访问非静态成员需要对象引用`库存.ItemID'

我想将Inventory中的ItemID更改为1。

类别ItemSwordUneq:

using UnityEngine;
using System.Collections;
public class ItemSwordUneq : MonoBehaviour 
{
    public bool canPickup = false;
    void Update () 
    {
        if(canPickup == true && Input.GetKeyDown(KeyCode.F))
        {
            GameObject player = GameObject.Find("Player");
            Inventory inventory = player.GetComponent<Inventory>();
            Inventory.ItemID = 1;
            Destroy(gameObject);
        }
    }
    void OnTriggerEnter(Collider other)
    {
        canPickup = true;
    }
    void OnTriggerExit(Collider other)
    {
        canPickup = false;
    }
    void OnGUI()
    {
        if(canPickup == true)
        {
            GUI.Label(new Rect(250, 250, 300, 20), "Press 'F' To Pick Up Sword");
        }
    }
}

类别Inventory:

using UnityEngine;
using System.Collections;
public class Inventory : MonoBehaviour 
{
    public bool hasItem = false;
    public int ItemID;
}

我做错了什么?如有任何答案,我们将不胜感激。

Unity C# Problems

您可能想要编写inventory.ItemID = 1;而不是Inventory.ItemID = 1;

如果您想将player.GetComponent<Inventory>();的结果的ItemId设置为1。

您试图在类Inventory上调用一个方法,而不是在对象inventory上调用,如果该方法不是静态的,则这没有任何意义。