0
\$\begingroup\$

So I'm trying to change the function of a button by a clickable method in Unity. I'm using a GetComponent to access the button component of the game object and then assign the clickable function.

But I get this error:

GetComponent requires that the requested component 'Button' derives from MonoBehaviour or Component or is an interface

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UIElements;
using Button = UnityEngine.UIElements.Button;

public class Button_System : MonoBehaviour
{
    public GameObject Button01;
    public GameObject Image01;

    public void Start()
    { 
        Button01.GetComponent<Button>().clickable = new Clickable(Example);
    }

    public void Example()
    {
        Image01.SetActive(false);
    }
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

See the documentation for the UI Toolkit:

In UI Toolkit, the visual tree is virtual and doesn’t use GameObjects. You can no longer build or view the UI hierarchy in the hierarchy view, but it removes the overhead of using a GameObject for each UI element.

...

Since there are no GameObject or components in UI Toolkit, you can’t directly assign references to a control in the Editor. They must be resolved at runtime using a query function. Instead, access the Visual Tree via the UIDocument component.

So you cannot use GameObject.GetComponent() to get access to a UIElements.Button component, because this kind of button is not a component that gets attached to a GameObject.

Instead, as shown in the docs, you need to take a reference to the UIDocument component at the root of the visual tree, and use a query:

public UIDocument uiDoc; // Assign this in the Inspector.

public void Start()
{ 
    // Finds a Button-type element with a specific name under the root.
    var button = uiDoc.rootVisualElement.Query<Button>("element name");
    // Now do what you want with the button.        
}
\$\endgroup\$
1
  • \$\begingroup\$ Thanks! it worked \$\endgroup\$
    – curry girl
    Dec 17, 2022 at 23:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .