Jar*_*cio 3 c# unity-game-engine
我几乎失去了所有希望。我想做的基本上是实例化一个预制件,它基本上是一个带有图像的按钮,一旦实例化,我想设置一个要调用的 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我试图获取游戏对象并前后投射它,但什么也没有,我需要你们的帮助!提前致谢
小智 6
你遇到这个问题是因为你使用的是Buttonfrom UnityEngine.UIElements,据我所知,它还不支持游戏内按钮(它供自定义编辑器使用)。使用UnityEngine.UI并替换:
button.clicked += manguito;
Run Code Online (Sandbox Code Playgroud)
和
button.onClick.AddListener(manguito);
Run Code Online (Sandbox Code Playgroud)