Search code examples
c#c#-4.0unityscriptunity-game-engine

How to show GUI when Click on the Object


I have a cube and a GUI for changing color of the cube and its working perfectly,Like when i play my scene GUI appear on the screen and change the color whatever i want,the thing which i want is when i click on the cube then GUI appear on the screen then i am able to change the colors. please edit my code for this scenario thanks. Here's my code:

using UnityEngine;
using System.Collections;
public class ChangeColour : MonoBehaviour
public Texture2D colourTexture;
public Renderer colouredCube;
    private Rect textureRect = new Rect (15, 15, 100 , 200);
void OnGUI ()
{
GUI.DrawTexture (textureRect, colourTexture);

    if (Event.current.type == EventType.MouseUp) {
        Vector2 mousePosition = Event.current.mousePosition;

        if (mousePosition.x > textureRect.xMax || mousePosition.x < textureRect.x || mousePosition.y > textureRect.yMax || mousePosition.y < textureRect.y) {
            return;
        }
float textureUPosition = (mousePosition.x - textureRect.x) / textureRect.width;
        float textureVPosition = 1.0f - ((mousePosition.y - textureRect.y) / textureRect.height);

        Color textureColour = colourTexture.GetPixelBilinear (textureUPosition, textureVPosition);
        //colouredCube.material.color = textureColour;
        changeMeshColour (textureColour);
    }
}
void changeMeshColour (Color newColor)
{
    Color[] colorArray = new Color[colouredCube.GetComponent<MeshFilter> ().mesh.vertexCount];

    for (int i = 0; i < colorArray.Length; i++) {
        colorArray [i] = newColor;
    }

    colouredCube.GetComponent<MeshFilter> ().mesh.colors = colorArray;
}

Image


Solution

  • Put this script on your cube:

    public class CubeScript : MonoBehaviour
    {
        public GameObject ui;        
    
        void OnMouseDown()
        {
            ui.SetActive(!ui.activeSelf);    // or just true if no toggle
            // or 
            ui.enabled = !ui.enabled;        // for older versions
        }
    }
    

    Additionally your cube needs a collider (it should have a BoxCollider already if you used the default cube).

    Then drag the ui gameobject into the public variable in the inspector.

    Also set the gameobject to disabled in the inspector of course.