Tuesday, May 30, 2017

Finding UI Button from Canvas Gameobject in Unity 5.6

So in this scene, I have canvas with two buttons as shown in the picture below
This restart button has a tag 'restart_tag' and exit with 'exit_tag' button...

And in this scene, I want to reference to my buttons using variabel in my script and this variabel is a private var not a public, so I can't drag and drop button because it's a private. So what we can do for achieving this ?
We have several ways... :)
First... We can use a public function from canvas class namely GetComponentsInChildren<Button>(), this function will gonna return all of the button within this canvas as an array. Here is the example code :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class canvas_sc1 : MonoBehaviour {

	private Button[] buttons;
	private Canvas cvs;
	// Use this for initialization
	void Start () {
		cvs = GetComponent<Canvas>();
		buttons = cvs.GetComponentsInChildren<Button> ();
		Debug.Log (buttons[0].tag);
		Debug.Log (buttons[1].tag);
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

When we run the game, we'll see that button[0] contains button for restart and another for exit
Another function that we can use is GetComponents. Here is the example :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class canvas_sc1 : MonoBehaviour {

	private Button[] buttons;
	private Button button;
	private Canvas cvs;
	// Use this for initialization
	void Start () {
		cvs = GetComponent<Canvas>();
		buttons = cvs.GetComponents<Button>();
		Debug.Log (buttons);
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}
but unfortunately, for unity 5.6, GetComponents doesn't work... :v
So we can just use GetComponentsInChildrend ... :)

Video :

No comments:

Post a Comment