I'd like Unity to get a specific button with:
But how do I get a specific button with a name?
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It only takes a minute to sign up.Sign up to join this community
someObject.GetComponent gets a component attached to
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.