我想在 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/