- Home /
UnityEvent.Invoke Generates Garbage?
Hi!
I created a simple Trigger component:
public class Trigger : MonoBehaviour {
public enum DisableMode
{
None,
Enter,
Exit
}
public DisableMode disableMode;
[System.Serializable]
public class TriggerEvent : UnityEvent { }
public TriggerEvent onTriggerEnter;
public TriggerEvent onTriggerExit;
// privates
private Collider m_collider;
private bool m_triggered;
void Awake()
{
m_collider = GetComponentInChildren<Collider>();
}
void OnEnable()
{
m_collider.enabled = true;
m_triggered = false;
}
public void Nothing()
{
}
void OnTriggerEnter(Collider other)
{
if (m_triggered)
return;
m_triggered = true;
onTriggerEnter.Invoke();
if (disableMode == DisableMode.Enter)
m_collider.enabled = false;
}
void OnTriggerExit(Collider other)
{
onTriggerExit.Invoke();
if (disableMode == DisableMode.Exit)
m_collider.enabled = false;
}
}
I created the Nothing method for demonstration purpose and assigned it to onTriggerEnter event:
As you can see from this screenshot, Invoking an event with an empty action will generate 0.6KB garbage. Is there something I'm doing wrong? I'm sure this shouldn't happen.
Thank you!
$$anonymous$$B is not that much garbage unless you are planning on calling this a lot (and besides there are other functions that create relatively more garbage than this).
Answer by kaplica · Sep 13, 2017 at 08:35 PM
If you are using less than 2 listeners use C sharp events and if more then unity events. Unityevents creates garbage when dispatched (the first time) where C# events do not.
C sharp events tend to be faster than unitys anyway.
Hi @kaplica
Thank you for your answer!
I have 2 questions about it: 1. Is there any way to expose a C# event in the inspector? (This is almost mandatory for what I'm trying to achieve with the Trigger component.) 2. Could you clarify what you are referring to with If you are using less than 2 listeners use C sharp events and if more then unity events? Less than 2 listeners in the whole scene? Or on the same object? I'm placing the Trigger component on stuff the player can collect in a platformer game.