在为《城市:天际线》开发模组时,我遇到了一个问题。
据我所知,我的大部分代码都运行良好 - 但到目前为止,我还没有测试它。这是因为当我添加到 UI 的按钮被单击时,它应该按顺序全部调用。此按钮上的点击事件未调用我分配给它的处理程序。
这是我创建按钮的地方:
public class LoadingExtension : LoadingExtensionBase
{
public override void OnLevelLoaded(LoadMode mode)
{
Debug.LogDebugMessage("Adding 'Generate City Report' button to UI");
// Get the UIView object. This seems to be the top-level object for most
// of the UI.
var uiView = UIView.GetAView();
// Add a new button to the view.
var button = (UIButton)uiView.AddUIComponent(typeof(UIButton));
// Set the text to show on the button.
button.text = "Generate City Report";
// Set the button dimensions.
button.width = 250;
button.height = 30;
// Style the button to look like a menu button.
button.normalBgSprite = "ButtonMenu";
button.disabledBgSprite = "ButtonMenuDisabled";
button.hoveredBgSprite = "ButtonMenuHovered";
button.focusedBgSprite = "ButtonMenuFocused";
button.pressedBgSprite = "ButtonMenuPressed";
button.textColor = new Color32(255, 255, 255, 255);
button.disabledTextColor = new Color32(7, 7, 7, 255);
button.hoveredTextColor = new Color32(7, 132, 255, 255);
button.focusedTextColor = new Color32(255, 255, 255, 255);
button.pressedTextColor = new Color32(30, 30, 44, 255);
// Enable button sounds.
button.playAudioEvents = true;
// Place the button.
button.transformPosition = new Vector3(-1.0f, 0.97f);
// Respond to button click.
// NOT GETTING CALLED
button.eventClick += ButtonClick;
}
public void ButtonClick(UIComponent component, UIMouseEventParameter eventParam)
{
Debug.LogWarningMessage("HIGH LOGIC: Beginning report generation.");
string now = DateTime.Now.ToFileTime().ToString();
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filename = filepath + "\\CityReport-" + now + ".xlsx";
Output fileCreator = new Output(filename);
fileCreator.GenerateReport();
}
}
根据documentation我一直在关注,使用
button.eventClick += ButtonClick;
应该添加 ButtonClick
作为按钮的点击处理程序。但是,单击按钮什么也不做。处理程序开始时的调试消息(“HIGH LOGIC”消息)不会显示(注意:之前关于将按钮添加到 UI 的调试消息会显示)。游戏的调试面板或 VS 中均未显示任何错误消息。
我也尝试过使用 new MouseEventHandler(ButtonClick)
,因为 VS 内联文档告诉我 eventClick
的类型是 MouseEventHandler
。这不会显示 VS 或游戏中的任何错误,但也不起作用。
(注意:是 official documentation,但它几乎没用。)
这里有人有使用 C:S API 的经验吗?为什么没有调用此事件?
最佳答案
您可以尝试后退一小步,检查不同的 UI 元素是否有效;例如,按照添加 UILabel 的示例.向这个注册一个点击事件处理程序可能会起作用,因为有一个实际的例子可以遵循;虽然,文档说将此代码放在 Start 方法中。我不确定,但也许您代码中的 UIButton 也应该放在 Start 方法中。
顺便说一句,我偶然发现了这个链接 debugging . Skylines 似乎有自己的调试消息系统。
我在您的代码中确实注意到,第一个 Debug 语句使用的方法与第二个 Debug 语句不同:
- Debug.LogDebugMessage("将'生成城市报告'按钮添加到 UI");
- Debug.LogWarningMessage("高逻辑:开始生成报告。");
这可能没有任何区别,但我会通过将它移动到 Debug.LogDebugMessage 所在的位置来测试 Debug.LogWarningMessage 调用,看看它是否真的有效。
根据极其简洁的文档,有一个名为 output_log.txt 的日志文件,也许此文件中可能包含一些信息。
关于c# - 为什么这个添加的 UI 按钮的事件没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30402751/