GameCrafter-游戏工匠 2024-11-10 15:07 采纳率: 75%
浏览 77

Unity运行时Button无法触发onclick怎么办?

我在制作游戏背包系统时想要实现点击Slot使得他的子物体Select设置为True而上一个选中的Select为false实现起来不难但是我在测试的时候发现无论我怎么点击按钮都无法触发OnClicked,我还debug了一下还是无法触发为什么,以下是部分代码和照片

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InvenSlot : MonoBehaviour
{
    public int slotID;
    public Item slotItem;
    public Image slotImage;
    public Text slotNum;
    public GameObject ItemInSlot;
    public GameObject Select;
    
    public void ItemOnClicked()
    {
        if(PlayerInventoryManager.current != null)
        {
            PlayerInventoryManager.current.GetComponent<InvenSlot>().CloseSelect();
        }
        OpenSelect();
        Debug.Log("选中当前物品!");
    }
    public void OpenSelect()
    {
        Select.SetActive(true);
    }
    public void CloseSelect()
    {
        Select.SetActive(false);
    }
    public void SetupSlot(Item item)
    {
        if(item == null)
        {
            ItemInSlot.SetActive(false);
            return;
        }
        ItemInSlot.SetActive(true);
        
        slotImage.sprite = item.itemImage;
        slotNum.text = item.num.ToString();
    }
}


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

public class PlayerInventoryManager : MonoBehaviour
{
    public Inventory MyBag;
    static PlayerInventoryManager instance;
    public GameObject SlotGrid;
    public List<GameObject> SlotList = new List<GameObject>();
    public GameObject EnmptySlot;
    public static GameObject current;
    
    void Awake()
    {
        if(instance != null)
        {
            Destroy(this);
        }
        instance = this;
    }
    private void OnEnable()
    {
        RefreshInventory();             
    }
    
    void Update()
    {
        RefreshInventory();      
    }
    
    public static void RefreshInventory()
    {
        for(int i = 0; i < instance.SlotGrid.transform.childCount; i ++)
        {
            if(instance.SlotGrid.transform.childCount == 0) break;
            Destroy(instance.SlotGrid.transform.GetChild(i).gameObject);
            instance.SlotList.Clear();
        }
        for(int i = 0; i < 3; i ++)
        {
            
            instance.SlotList.Add(Instantiate(instance.EnmptySlot));
            instance.SlotList[i].transform.SetParent(instance.SlotGrid.transform);
            instance.SlotList[i].GetComponent<InvenSlot>().slotID = i;
            instance.SlotList[i].GetComponent<InvenSlot>().SetupSlot(instance.MyBag.itemList[i]);
        }
        
    }
}

img

img

  • 写回答

1条回答 默认 最新

  • 先生沉默先 2024-11-12 17:54
    关注

    试试使用代码绑定按钮的事件。

        public Button myButton;
    
      void Start()
        { 
     myButton.onClick.AddListener(OnButtonClick);
            }
       //当按钮被点击时会调用这个方法
        void OnButtonClick()
        {
            Debug.Log("按钮被点击了!");
        }
    
    评论

报告相同问题?

问题事件

  • 创建了问题 11月10日