- Home /
Click/touch object to enable/disable buttons inside Canvas
hello,
I want to make a simple switch to enable or disable UI buttons by clicking on any gameObject. (Using Unity 5.3.5). I have multiple objects in my game view,and there are separate UI buttons inside the canvas for each of the object. Whenever I click or touch on any object it will show the UI related to that object.
using the code bellow i am able to click only on Single object (there is also no touch input), i want to add multiple objects with UI switch...
How to write it inside this code.. please help
using UnityEngine;
using System.Collections;
using UnityEngine .UI;
public class click1object : MonoBehaviour {
void Start () {
}
void Update(){
if (Input.GetMouseButtonDown(0)){ // if left button pressed...
Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)){
print ("clicked");
}
}
}
}
Answer by 334499p · Aug 21, 2016 at 08:10 PM
Hey @nitesh, you can name the objects and the buttons similar things so that when you click an object it takes its name and points to its button in the canvas.
1) Name all your buttons the same thing as your objects with the suffix of "-button." So if you had 1 object and 1 button in your scene, then object 1 would be named "object1" and the linked button would be named "object1-button".
2) In your script, get the name of the object:
string objectName = hit.transform.gameObject.name;
3) Create the reference string to your button by adding the suffix to the objectName string:
objectName = objectName + "-button";
4) Get the button in the scene with your objectName string:
Button myButton = GameObject.Find(objectName).GetComponent<Button>();
5) Switch the button on/off:
myButton.interactible = !myButton.interactible;
Place all of the above code within the raycast if statement.