unity-game-engine - 如何构建一个可跨场景重用的 Unity UI 组件

标签 unity-game-engine

我想在 Unity 中构建一个可跨多个场景使用的 UI 模式,我如何实现这一目标,稍后可能将其构建为人们可以在其 Unity 项目中使用的独立库。有这方面的教程吗?

最佳答案

探索这个repo 。它是可用的,但目前处于实验阶段。 UIElements 正在成为 Unity 的新标准,因此几周/月内就会有预览包。

如果你想使用当前的 UI,你可以为每个可重用窗口创建单独的场景并以附加方式打开它们,将参数和回调传递给静态方法,请参阅我的 example

线路

public class ResultLineEntity {
    public int Place;
    public readonly string Title;
    public readonly TimeSpan Time;
    public ResultLineEntity(string title, TimeSpan time, int? place = null) {
        if (place != null) Place = place.Value;
        Title = title;
        Time = time;
    }
}

窗口

public class ResultsUi : MonoBehaviour {
    public static ResultLineEntity[] Lines
    {
        get => _lines;
        set
        {
            _lines = value;
            OnLinesChange?.Invoke();
        }
    }
    private static ResultLineEntity[] _lines;

    public static UnityEvent OnLinesChange { get; private set; } = new UnityEvent();

    [SerializeField] private Transform root;
    [SerializeField] private ResultLineUi prefab;

    private void Awake() {
        SetLines();
        OnLinesChange?.AddListener(SetLines);
    }

    public void SetLines() {
        if (Lines==null || Lines.Length < 1) return;

        foreach (var child in root.GetComponentsInChildren<ResultLineUi>()) {
            Destroy(child.gameObject);
        }

        var resultsOrdered = Lines.OrderBy(x => x.Time).ToArray();
        for (var index = 0; index < resultsOrdered.Length; index++) {
            var line = resultsOrdered[index];
            line.Place = index + 1;
            var currentLine = Instantiate(prefab, root);
            currentLine.SetLine(line);
        }
    }
}   

示例

ResultsUi.Lines = lines;
SceneManager.LoadScene(ResultsSceneName, LoadSceneMode.Additive);

关于unity-game-engine - 如何构建一个可跨场景重用的 Unity UI 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60061428/

相关文章:

c# - 为什么这会导致 InvalidOperationException : Out of sync?

ios - 从 xcode 更新应用程序而不是全新安装

unity-game-engine - 实例化预制件丢失脚本引用

c# - 如何知道图像用于哪个预制件

c# - 使用 google play games 检索玩家排名

unity-game-engine - Unity3D 旋转瓶子

unity-game-engine - Unity3D 在新 UI 中实例化预制件列表

user-interface - 如何在Unity顶部显示ui元素

node.js - 在 HttpsCallableResult 完成之前等待所有回调返回

unity-game-engine - UI 文本检查器可以在 Unity3D 中扩展吗?