Register an event for inactive object

Hi, I am not sure about the way I am implementing events for inactive objects.
For instance, I have my Inventory GUI listening to the Inventory script, and I want to use this event to change the open or close status.
But how can I register it if it’s not active at first?
I have some work around for now but I want to see what you guys usually do.

I have this in OnEnable or Start method.
PlayerInventory.Instance.OnInventoryOpen += OpenOrCloseInventory;

Do the subscribe in OnEnable(); and the unsubscribe in OnDisable();

It is a well-tried and true method.

“Inactive or not” doesn’t matter at that point.

Inactive object should not do anything, including receiving events. You’ll want to have another active object that receive the event, and enable the inactive objects and give it any related data when needed.

The usual pattern for dealing with this is to always update the state of the component during the OnEnable event. This way even if the object missed some events while it was inactive, it’ll still be up-to-date whenever its active:

void OnEnable()
{
	PlayerInventory.OnInventoryOpen += UpdateOpenState;
	PlayerInventory.OnInventoryClose += UpdateOpenState;
	UpdateOpenState(); // <- update state every time when becoming active
}

If somehow you are in a situation, where other objects might access members on the component while it is inactive, then a viable workaround for that would be to initialize the object on-the-fly if needed when any of its public members are accessed:

public bool IsOpen
{
	get
	{
		if(!setupDone)
		{
			Setup();
		}

		return isOpen;
	}
}

But you generally speaking shouldn’t ever find yourself in a situation where members are being accessed on inactive objects. Rather than doing this, it’s better to first take a step back and re-evaluate your architecture, and see if you could somehow make this impossible to happen in the first place.