首页 > 解决方案 > GetComponent 要求请求的组件 'Button' 派生自 MonoBehaviour 或 Component 或者是一个接口

问题描述

我几乎失去了所有希望。我想要做的基本上是实例化我拥有的一个预制件,它基本上是一个带有图像的按钮,一旦实例化,我想设置一个要调用的 onClick 函数,但它一直告诉我这个错误:

GetComponent 要求请求的组件 'Button' 派生自 MonoBehaviour 或 Component 或者是一个接口

我不明白我做错了什么,这是我的代码:

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

public class InventoryCoordinator : MonoBehaviour
{
    // Start is called before the first frame update
    public GameObject prefabPocion;
    void Start()
    {
        GameObject panelInventuario = GameObject.FindGameObjectWithTag("Hotbar");
        if (panelInventuario)
        {
            GameObject primerSlot = panelInventuario.transform.GetChild(0).gameObject;
            GameObject segundoSlot = panelInventuario.transform.GetChild(1).gameObject;
            GameObject tercerSlot = panelInventuario.transform.GetChild(2).gameObject;
            var newPocion = Instantiate(this.prefabPocion, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity);
            this.SetAndStretchToParentSize((UnityEngine.RectTransform)newPocion.transform.transform, (UnityEngine.RectTransform)primerSlot.transform.transform);
            var button = GameObject.FindWithTag("PotionFreeze").gameObject.GetComponent<Button>();
            button.clicked += manguito;
            //newPocion.transform.parent = primerSlot.transform;
        }
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void manguito()
    {
        Debug.Log("full maracaton");
    }

    public void SetAndStretchToParentSize(UnityEngine.RectTransform _mRect, UnityEngine.RectTransform _parent)
    {
        _mRect.anchoredPosition = _parent.position;
        _mRect.anchorMin = new Vector2(1, 0);
        _mRect.anchorMax = new Vector2(0, 1);
        _mRect.pivot = new Vector2(0.5f, 0.5f);
        _mRect.sizeDelta = _parent.rect.size;
        _mRect.transform.SetParent(_parent);
        _mRect.localScale = new Vector3(1f, 1f, 1f);
    }
}

我已经尝试获取游戏对象并将其向后和向前投射,但什么也没有,我需要你们的帮助!提前致谢

标签: c#unity3d

解决方案


您遇到此问题是因为您使用的是Buttonfrom UnityEngine.UIElements,afaik 尚不支持游戏按钮(它用于自定义编辑器)。改为使用UnityEngine.UI,并替换:

button.clicked += manguito;

button.onClick.AddListener(manguito);

推荐阅读