- Home /
How to use UnityEvent with duplicate gameobjects?
I have a UnityEvent that sets the animator speed of a gameobject to zero. I also have 30 duplicates of a certain gameobject throughout the scene (it's just a prefab that I dragged and dropped in different places). How can I make the UnityEvent apply to all of these objects? I tried just dragging the prefab to the event list, but it won't work. I could add all 30 of the objects to the list, but that seems impractical. Is there a better way of doing this?
Answer by hexagonius · Mar 20, 2018 at 07:46 PM
if you don't want to do this by hand, you'd need to do this by code.
you have several options. You could create an array of those listener classes in the same script as the event. You can then drag all of the listeners into the inspector array while that is locked (tiny lock on the upper right in the inspector). then register all of their relevant methods to the event by code. You could also make the event static. then all the listener have access to it from their scripts via the class the event is in. You have to be extra careful to not miss removing them on destroy.
I think the second way you mentioned is probably best. I’ll just do away with the UnityEvent and replace it with a C# event, like public event Action onAction inside my GameManager, then attach a script to my object that subscribes the relevant method to that event. I’ll also make sure to unsubscribe from it when the object is destroyed. Thanks.