单击对象时如何显示 GUI

How to show GUI when Click on the Object

我有一个立方体和一个用于改变立方体颜色的 GUI 并且它工作得很好,就像当我播放我的场景时 GUI 出现在屏幕上并随心所欲地改变颜色,我想要的是当我单击立方体然后 GUI 出现在屏幕上然后我可以更改颜色。请为此场景编辑我的代码谢谢。 这是我的代码:

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

将此脚本放在您的多维数据集上:

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
    }
}

此外,您的立方体需要一个碰撞器(如果您使用默认立方体,它应该已经有一个 BoxCollider)。

然后将 ui 游戏对象拖到检查器中的 public 变量中。

当然还要在检查器中将游戏对象设置为禁用。