Click/touch object to enable/disable buttons inside Canvas (171475)

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");
           
            }
        }
    }
}

Although true, this path is only known by the application instance from inside Unity. Third party tools, launchers, patchers, and middleware may not be able to correctly guess the path. And there are many cases where this is not the right solution. Sometimes it is required for the application to be aware of its current root structure in terms of the root binary executable. However, the OP was seeking for it to go side-by-side with the executable / player package, not sure this addresses the question.

1 Answer

1

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();

  5. Switch the button on/off:

    myButton.interactible = !myButton.interactible;
    Place all of the above code within the raycast if statement.