【问题标题】:How to dynamically create button using NGUI (Unity)如何使用 NGUI (Unity) 动态创建按钮
【发布时间】:2023-03-22 04:17:01
【问题描述】:

我是 Unity 和 NGUI 的新手,我不知道如何将自定义图集和精灵动态分配到按钮中。

using UnityEngine;
using System.Collections;

public class createButton : MonoBehaviour {
    public createButton(){
        GameObject newButton = new GameObject ();
        newButton.name = "newButton" + 1;

        //go.AddComponent<UISprite> ();
        newButton.AddComponent<UIButton> ();
        newButton.AddComponent<UISprite> ();
    }
}

【问题讨论】:

  • 您是否有理由动态执行此操作而不是实例化预制件?
  • Dan Puzey:我想用一个预制件动态创建不同的按钮,这会造成混乱吗?或者我现在做这件事太难了。

标签: c# button dynamic unity3d ngui


【解决方案1】:

使用预制件:

public class createButton : MonoBehaviour {
    public GameObject myNguiButtonPrefab;
    private int nextId;

    public createButton(){
        GameObject newButton = (GameObject)Instantiate(myNguiButtonPrefab);
        newButton.name = "newButton" + (nextId++);

        MyButtonScript buttonScript = newButton.GetComponent<MyButtonScript>();
        buttonScript.Setup(/* some parameters */);
    }
}

因此,在场景中创建一个游戏对象并添加您的 createButton 脚本。然后使用 NGUI 小部件向导创建一个按钮并将其保存为预制件。然后,将该预制件链接到检查器中的 createButton.myNguiButtonPrefab 字段。最后,将自定义脚本添加到按钮预制件中,该脚本将根据您关心的任何参数处理单击按钮时发生的情况,如下所示:

public class MyButtonScript : MonoBehaviour {
    public void Setup(/* Some parameters */){
        // Do some setting up
        UISprite sprite = GetComponent<UISprite>();
        sprite.spriteName = "someSpriteBasedOnTheParametersPassed";
    }

    void OnClick(){
        // Do something when this button is clicked based on how we set this button up
    }
}

如果你想要真正的花哨,你可以把你的 createButton 改成这样:

public class createButton : MonoBehaviour {
    public MyButtonScript myNguiButtonPrefab;
    private int nextId;

    public createButton(){
        MyButtonScript newButton = (MyButtonScript )Instantiate(myNguiButtonPrefab);
        newButton.name = "newButton" + (nextId++);
        newButton.Setup(/* some parameters */);
    }
}

【讨论】:

    猜你喜欢
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多