GetKeyDown 发送多个输出

GetKeyDown sends multiple outputs

具体来说,它会发送尽可能多的输出,因为其中包含允许它们进行交互的代码的对象,即使我在不​​看任何东西时按 E。我想制作一个库存系统,但这会导致所有具有此代码的对象都与之交互。如果有帮助,我包括了我用于该系统的所有脚本。我真的不知道我做错了什么

交互代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System;

public class Interactable : MonoBehaviour
{
public LayerMask interactableLayerMask;

//ITEM VARIABLE
public Item item;

//PICK UP RADIUS
public float radius = 4f;

public void Interact()
{
    Debug.Log("Interacted with " + transform.name);
    PickUp();
}

//PICK UP INTERACTION
void PickUp()
{
    Debug.Log("Picking up " + item.name);
    bool wasPickedUp = Inventory.instance.Add(item);

    if (wasPickedUp)
        Destroy(gameObject);
}


//INTERACTION
void Update()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        Debug.Log("Added item -----------------------------------------");
        RaycastHit hit;

        if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, radius))
        {
            Interactable interactable = hit.collider.GetComponent<Interactable>();
            if (interactable != null)
            {
                Interact();
            }
        } else
        {
            Debug.Log("Nothing");
        }
    }
}
}

库存代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Inventory : MonoBehaviour
{
#region Singleton

public static Inventory instance;

void Awake()
{
    if (instance != null)
    {
        Debug.LogWarning("More than one instance of Inventory found!");
        return;
    }
    instance = this;
}
#endregion

public delegate void OnItemChanged();
public OnItemChanged onItemChangedCallback;
    

public int space = 20;

public List<Item> items = new List<Item>();

public bool Add (Item item)
{
    if (!item.isDefaultItem)
    {
        if (items.Count >= space)
        {
            Debug.Log("Note enough space in inventory");
            return false;
        }
        else
        {
            items.Add(item);

            if (onItemChangedCallback != null)
                onItemChangedCallback.Invoke();
        }
    }
    return true;
}

public void Remove(Item item)
{
    items.Remove(item);

    if (onItemChangedCallback != null)
        onItemChangedCallback.Invoke();
}

}

商品代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName = "New Item", menuName = "Inventory/Item")]

public class Item : ScriptableObject
{
    new public string name = "New Item";
    public Sprite icon = null;
    public bool isDefaultItem = false;
}

据我了解,您的代码会为场景中的每个对象进入 Input.GetKeyDown(KeyCode.E),但不会将其添加到清单中。

那是因为你在Interactableclass中使用了Update函数,这是你的对象。相反,尝试将完全相同的代码块移动到您的库存 class。确保创建交互方法 public,以便调用它。