C# 统一委托事件
我想当按钮被点击时,它会在上面显示一些GUI按钮。我已经尝试过委托,但是没有触发事件(我的意思是没有显示GUI按钮) 以下是我正在使用的代码: 下面的代码是在我运行游戏时显示GUI按钮C# 统一委托事件,c#,events,delegates,unity3d,C#,Events,Delegates,Unity3d,我想当按钮被点击时,它会在上面显示一些GUI按钮。我已经尝试过委托,但是没有触发事件(我的意思是没有显示GUI按钮) 以下是我正在使用的代码: 下面的代码是在我运行游戏时显示GUI按钮 public class IItemDatabase : MonoBehaviour { public delegate void Action(); // Set the event for the button public static event Action onClicked; //
public class IItemDatabase : MonoBehaviour
{
public delegate void Action(); // Set the event for the button
public static event Action onClicked; // The event for when the button has been clicked
protected virtual void OnGUI()
{
// Call the SetStyle method
SetStyle();
// Set the GUIContent as the tooltip
GUIContent buttonText = new GUIContent("Open Shop");
// Set the GUIContent as the tooltip
GUIContent buttonTexts = new GUIContent("Open Inventory");
// This GUILayoutUtility is useful because it is to fit the content
Rect buttonGUI = GUILayoutUtility.GetRect(buttonText, "Button");
// This GUILayoutUtility is useful because it is to fit the content
Rect buttonGUIs = GUILayoutUtility.GetRect(buttonTexts, "Button");
// Set where have to the Rect displayed
buttonGUI.x = 5;
buttonGUI.y = Screen.height - 25;
// Set where have to the Rect displayed
buttonGUIs.x = 125;
buttonGUIs.y = Screen.height - 25;
// If the button has been clicked
if (GUI.Button(buttonGUI, buttonText, style))
{
if (onClicked != null)
{
onClicked();
}
}
if (GUI.Button(buttonGUIs, buttonTexts, style))
{
if (onClicked != null)
{
onClicked();
}
}
// End of the clicked button event
}
}
单击按钮后,我希望它显示以下内容:
public class IInventory : MonoBehaviour
{
protected virtual void OnEnable()
{
IItemDatabase.onClicked += DoGUI;
}
protected virtual void OnDisable()
{
IItemDatabase.onClicked -= DoGUI;
}
protected virtual void DoGUI()
{
Rect slotRect = new Rect(x * 35 + (Screen.width / 3) + 50, y * 35 + (Screen.height / 3) - 10, 30, 30);
GUI.Box(slotRect, GUIContent.none);
}
}
但是,当我单击该按钮时,它假定在IInventory类中触发DoGUI(),但它没有运行该函数
我如何解决这个问题
多谢各位
非常感谢你的回答 您的问题不在于事件或委托,而在于对
OnGUI()
工作原理的误解
每个帧可能会调用该方法数次,但单击按钮后,onClicked
事件只会调用一次。因此,您的库存仅在几毫秒内可见
有几种方法可以解决这个问题。您的目标是在每次OnGUI()
调用期间调用DoGUI()
,只要您希望显示库存。您可以引入一个布尔值来保存清单菜单的状态,并决定菜单是否应可见。如果您想让打开库存
按钮切换菜单,您可以尝试类似的方法
public class IItemDatabase : MonoBehaviour
{
public static event Action onClicked; // The event for when the button has been clicked
private bool showInventory = false;
protected virtual void OnGUI()
{
// I removed your other code to simplify the example
if (GUI.Button("Open Inventory"))
{
// toggle the status
showInventory = !showInventory
}
if (showInventory && onClicked != null)
{
onClicked();
}
}
}
是否保留事件取决于您的应用程序。如果您保留它,我会将其重命名为
showinentorygui
或类似的名称,以更好地反映其意图。另一方面,您可以简单地删除事件,直接调用方法IInventory.DoGUI()
。那么,先生,我应该怎么做才能解决这个问题呢?很抱歉迟了答复。感谢you@Kaoru我添加了一个可能解决方案的示例!谢谢你,先生!我用另一种方式做了这件事,没有使用委托。。非常感谢。