如何根据拾取的物品实现功能?

问题描述 投票:0回答:2

我想要一种在收集所有必需项后实现某个功能的方法。该代码用于拾取螺丝刀和刀具之类的物品,并且根据拾取物品的数量(两个)我想实现一个功能。

以下截图为拾取物品:

我尝试添加一个计数器,然后在启用图标后我增加了计数器,但它计数了一次。

取物代码如下:

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

public class PicUpTools : MonoBehaviour
{
    public GameObject objectWithPlayer,PicUpText;
    
    public RawImage objectRawImage;
    private int counter = 0;
    void Start()
    {
        objectWithPlayer.SetActive(false);
        objectRawImage.enabled = false;
        PicUpText.SetActive(false);
    }

    private void OnTriggerStay(Collider other)
    {
        if(other.gameObject.tag == "Player")
        {
            PicUpText.SetActive(true);
            if (Input.GetKey(KeyCode.E))
            {
                gameObject.SetActive(false);
                objectWithPlayer.SetActive(true);
                objectRawImage.enabled = true;
                counter++;
                PicUpText.SetActive(false);

                if (counter==2)
                {
                    Debug.Log("Elements have collected");
                }
            }
        }
    }

    private void OnTriggerExit(Collider other)
    {
        PicUpText.SetActive(false);
    }
}


有什么建议吗?

c# unity3d unityscript
2个回答
0
投票

我会在播放器脚本上添加一个公共的 addObject 函数,并在拾取对象时在 Pickup 类中调用它。

addObject 会在播放器脚本中增加一个 int 计数器,然后您可以检查它何时达到两个并调用您想要的任何函数。


0
投票

符合上一个问题的答案。这里,最好考虑一个

Dictionary
来记录物品的数量。
Dictionary<>
可以记录每个key的物品数量,所以每次获得物品后,在其成员编号上加一。

private Dictionary<Item, int> itemDictionary = new Dictionary<Item, int>(); // Define dictionary like this

private void OnTriggerStay(Collider other)
{
    if (Input.GetKeyDown(KeyCode.E)) // First Check KEY cuz of optimization
    {
        if(other.gameObject.TryGetComponent(out Item item))
        {
            item.PickUp();
            if (itemDictionary.ContainsKey(item))
            {
                itemDictionary[item]++;
                Debug.Log($"{name} has {itemDictionary[item]} of {item}.");
            }
            else
            {
                itemDictionary.Add(item, 1);
            }
            if (itemDictionary[item]==2) // check count of picked item.
            {
               Debug.Log($"Element: ({item.name}) have collected");
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.