所以我尝试使用开关大小写和枚举来更改按钮的文本,因为我不想使用太多的"如果";声明。但是,按钮文本没有正确显示。例如,actionButton1.text不是"保存游戏";但是";SAVE_NAME";。
ActionType.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum ActionType {
SAVE_GAME,
LOAD_GAME,
PAUSE_GAME
};
[CreateAssetMenu(fileName = "New Action", menuName = "Project/New Action")]
public class Action : ScriptableObject
{
public ActionType actionType;
public string actionName;
public void Awake() {
switch (actionType) {
case ActionType.SAVE_GAME:
actionName = "Save Game";
break;
case ActionType.LOAD_GAME:
actionName = "Load Game";
break;
case ActionType.PAUSE_GAME:
actionName = "Pause Game";
break;
}
}
}
System.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class System : MonoBehaviour {
public Text actionButton1;
public Text actionButton2;
public Text actionButton3;
public Action action1;
public Action action2;
public Action action3;
private void Start() {
refreshAction();
}
private void refreshAction() {
actionButton1.text = action1.actionName;
actionButton2.text = action2.actionName;
actionButton3.text = action3.actionName;
}
}
在您的情况下,我会使用延迟评估
public class Action : ScriptableObject
{
public ActionType actionType;
public string actionName
{
get
{
switch(actionType)
{
switch (actionType) {
case ActionType.SAVE_GAME:
return "Save Game";
case ActionType.LOAD_GAME:
return "Load Game";
case ActionType.PAUSE_GAME:
return "Pause Game";
}
return "invalid action type";
}
}
}
...
}
以便在更改代码时防止出现序列化问题。否则,您已经创建的可编写脚本的对象将保存旧数据(因为它们正在序列化(。
另一种方法是使用扩展方法使类似actionButton1.text = action1.actionType.ToReadableString();
的调用成为可能。