0
\$\begingroup\$

I'd like Unity to get a specific button with:

GetComponent<Button>().interactable

But how do I get a specific button with a name?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Remember, someObject.GetComponent gets a component attached to someObject.

If you don't lead with a specific object to look in, and just type GetComponent on its own, it refers to "this" object: the same one that the component running the script you're writing is attached to.

The best way to reference a specific button (or any other component) is to expose it as a member variable at the top of your class, outside of any methods:

public Button buttonIWantToUse;

This will create a slot in the Inspector where you can assign a reference to the button directly, with no searching at runtime.

If searching can't be avoided in your case, you can look up an object with a specific name in the active scene with:

var soughtObject = GameObject.Find("Some Name");
var buttonOnSoughtObject = soughtObject.GetComponent<Button>();

But I recommend avoiding looking up objects by name. It's not as fast or reliable as storing a reference, and it's easy to get downright baffling bugs that way.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks for this, and i just realised i could use this to fix some other bugs \$\endgroup\$ Commented Feb 1, 2021 at 0:41

You must log in to answer this question.

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