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


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


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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.