c# - 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);
}
}
我已经尝试获取游戏对象并将其向后和向前投射,但什么也没有,我需要你们的帮助!提前致谢
解决方案
您遇到此问题是因为您使用的是Button
from UnityEngine.UIElements
,afaik 尚不支持游戏按钮(它用于自定义编辑器)。改为使用UnityEngine.UI
,并替换:
button.clicked += manguito;
和
button.onClick.AddListener(manguito);
推荐阅读
- javascript - 我正在尝试使用 Particle js 在本网站的主要英雄部分显示粒子,但它不起作用
- javascript - React 将组件作为参数传递给函数
- php - PHP 如何从 DOMDocument 读取 XML 编码
- java - Apache POI:使用 Java 写入 excel:打开 Workbook,java.io.IOException:无法写入数据,文档似乎已经关闭
- c - sysmalloc 断言在 c 中失败
- spring - 如何从 Spring 控制器重定向到 React 页面
- codeigniter - 如何使用数组数据集从mysql数据库中获取数据
- java - 使用 jpa 存储库动态分片
- r - 让 Visual Studio 代码(自动)格式化 R 代码
- php - 带有 Laravel 的 Websocket - 连接建立错误:net::ERR_CERT_AUTHORITY_INVALID