If I have a SO where my Inventory items live, and on those items I want the option to invoke an event when something is used. How do I trigger that event from outside of the SO, say an InventoryManager script.
My event lives in a sealed class and is only active if a boolean returns true, also living in the sealed class.
For instance
public sealed class SomeAction
{
public bool useEvent;
public UnityEvent eventToInvoke; (if useEvent is true)
eventToInvoke.invoke();
}
InventoryManager
if(blahblahblah)
{
insert magic here :eyes:
}
InventoryManager would check on item use if useEvent is true and if it is, would run eventToInvoke.
Not sure if this is even possible, my brain says 50/50 but I’m probably nuts. I’m still digesting the world of Scriptable Objects lol
ScriptableObjects have OnEnable and OnDisable methods like monobehaviours so like you would do in those you would subscribe/unsubscribe to your event in these methods. Obviously your event needs to be static so it can be accessible outside the class. Though I’m not sure if that’s possible with unity events (probably is, I dont know). If I don’t want to expose such events in the inspector I normally go for regular .net events.
The thing you need to keep in mind is you can’t use a scriptable object on its own as a database. Even if you update the count of some item during a session you won’t be able to persist the data (I just assumed that’s what you are trying to do).
Sure you could do this, but it seems like it would be more efficient to just trigger the event in whatever code is triggering the use of the item. For example:
if(Input "Use" button is pressed)
{
UseItem(item);
TriggerEvent(item);
}
Gave it a try, you cannot trigger events from outside of their class. So, unless the class provides some sort of way to trigger event, can’t be done.
using System;
public sealed class SomeAction{
public bool flag;
public event System.Action ev;
public System.Action getInvoker(){
System.Action result = () => triggerEvent();
return result;
}
public void triggerEvent(){
if (flag)
ev?.Invoke();
}
}
public class Program{
public static void evInvoke(System.Action act){
Console.WriteLine("invoking");
act?.Invoke();
}
public static void Main(){
SomeAction act = new();
act.ev += () => Console.WriteLine("Event triggered");
act.flag = true;
act.triggerEvent();
evInvoke(() => act.triggerEvent());
evInvoke(act.getInvoker());
}
}
That s the whole point of events, one can just use a delegate if don’t want to use the main “feature” of events which is to prevent Invoke calls to be made outside of owner object. Other than that delegates are exactly the same as events.
Kinda irrelevant but what s the point of marking the action class sealed? (not from what it does perpective, but as of why)