【问题标题】:How to link a GUI Texture button to a script in Unity3d如何将 GUI 纹理按钮链接到 Unity3d 中的脚本
【发布时间】:2014-04-29 12:51:21
【问题描述】:

我需要一些帮助来制作自定义 GUI 纹理按钮,在 Unity3d for android 中触摸 3d 对象时启动脚本。

我有一个 GUI 按钮可以在按下时旋转 3d 模型。我得到的以下(C#)脚本工作正常。以编程方式创建按钮时:

using UnityEngine;
using System.Collections;

public class RotateButtonBheaviour : MonoBehaviour {

private bool mIsRotated = false;
private bool mMustRotate = false;
private GameObject Cube;

// Use this for initialization
void Start () {
    Cube = GameObject.Find ("MarkerObject");
}

// Update is called once per frame
void Update () {
    if (mMustRotate && !mIsRotated) {
        //Rotate all models 45 degrees around X
        if (Cube != null) {
            GameObject modelUnderChipsTrackable = Cube.transform.GetChild(0).gameObject;
            modelUnderChipsTrackable.transform.RotateAround(new Vector3(1,0,0), Mathf.PI/3);

        }
        mIsRotated = true;
        mMustRotate = false;
    }


public Texture btnTexture1;

void OnGUI() {
    if (!btnTexture1) {
        Debug.LogError("Please assign a texture on the inspector");
        return;
    }
    if (GUI.Button(new Rect(10, 10, 120, 30), btnTexture1))
        if (!mIsRotated) {
            mMustRotate = true;
        }

我想代替代码中的按钮来添加我的自定义 GUI 纹理按钮(名为 OrbitBtn),等等触摸,以启动 3d 模型围绕其轴旋转。

请给我一些关于如何实现该功能的建议。提前感谢大家的回答。

【问题讨论】:

    标签: c# android user-interface unity3d


    【解决方案1】:

    只需更改纹理 btnTexture1,或者您可以单击并将图像文件拖放到脚本中,因为您已将 btnTexture1 声明为公共。

    或者如果你想在 javascript 中做同样的事情,这里是示例代码。

    if(GUI.Button(Rect(Screen.width*.85,Screen.height*0,width,width),Resources.Load("pause") as Texture))
    {
    
    //Button press action
    }
    

    因此,在此示例代码中,我将图像(暂停。*)加载到按钮上。确保您的资产文件夹中有一个名为“Resources”的文件夹中的图像。

    【讨论】:

    • 您好 user3349513。谢谢你的提示。我是 Unity 的新手……那么,如何更改纹理 btnTexture1?我的 GUI 纹理按钮名为“OrbitBtn”。你的意思是把“btnTexture1”改成“OrbitBtn”吗?
    • 不,这取决于您如何创建 OrbitBtn,您是使用场景编辑器创建的吗?您在哪里将它们创建为游戏对象?如果是这样,请单击已添加上述脚本的对象,然后在右侧的检查器窗口中查看,您将看到一个对象 btnTexture1,因此您将 OrbitBtn 拖放到它上面。
    • 感谢 Karthik 的回答。我已经尝试了你的建议,没有任何反应。 OrbitBtn 在场景编辑器中创建为 GUI 纹理对象。我在 3d 模型上添加了脚本。我想要实现的是,仅在触摸按钮时才运行脚本。在上面的代码中,我可以做到这一点,但使用 GUI.Button,而不是 GUI Texture。我该怎么做?
    • 为什么要使用 GUI 纹理? GUI Button 接受一个作为按钮的纹理对象??
    • 您可以通过创建新皮肤来创建自定义 gui 皮肤。但是,我仍然不确定您要做什么,您想要按钮上的图像吗?然后只需将该图像用作纹理 btnTexture1 的值。如果你想使用图像作为按钮,那么我会尽快发布示例代码
    猜你喜欢
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    相关资源
    最近更新 更多