Your problem is not the event or the delegate, but a misunderstanding on how OnGUI()
works.
The OnGUI()
method might be called several times per frame, but your onClicked
event will only be called once after you clicked the button. So your Inventory is only visible for a few milliseconds.
There are several ways to solve the problem. Your goal is to call DoGUI()
during every OnGUI()
call as long as you want the inventory to be shown. You could introduce a boolean that saves the state of the inventory menu and decides whether the menu should be visible or not. If you want your Open Inventory
button to toggle the menu, you could try something like that
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();
}
}
}
If you want to keep the event depends on your application. If you keep it, I would rename it to showInventoryGUI
or something similar to better reflect its intention. On the other hand you could simply remove the event and just call the method IInventory.DoGUI()
directly.