Reputation: 155
I am new to Unity and was wondering if it was possible to check if a button component in present in the scene, this is like a UI test.
I am trying to do this using the Unity UI Test Automation tool.
Upvotes: 1
Views: 910
Reputation: 2442
While zyonneo answer is correct, GameObject.Find
can be slow if there is a lot of gameObjects.
What I would do instead is looking for the button component in the canvas children. For this you need a reference to the parent canvas of your button.
public GameObject MyCanvas;
void Start(){
if(MyCanvas.GetComponentInChildren<Button>() != null){
Debug.Log("Button found");
else {
Debug.Log("Button not found");
}
}
If you want more information about what is the most efficient way to find a gameObject, I recommend you to read this thread on Unity Formus.
Upvotes: 1
Reputation: 1389
Add the code where you want to check whether the button is present in Hierarchy.If you have added the button in the canvas you can find using the below code.Just type the exact name of the button.
By default when you add a button it will have the name "Button" so search with that parameter.Here I am adding a button by right clicking and then renaming it into "Btn01"
if(GameObject.Find("Btn01")!= null)
{
Debug.Log("Button is Present in Hierarchy");
}
else
{
Debug.Log("Button Not Present");
}
Upvotes: 0