Passing arguments to custom events through code

I have a Unity Event that expects a string argument. Here is some code and usage example:

[Serializable]
public class StringUnityEvent : UnityEvent<string> { }
public StringUnityEvent onLineUpdate;

private void DummyFunction()
{
    string text = "DummyText";
    onLineUpdate.Invoke(text);
}

When I look in the inspector, I can select the text field of a UI object like this:
6725965--773932--OnLineUpdate.PNG

However, I’d like to set that dynamically through code. So far, the best I got is something like this:

void Start()
{
    onLineUpdate.AddListener(SetTextField);
}

void SetTextField(string txt)
{
     if (useBubbles)
     {
            dialogueBubble.GetComponentInChildren<Text>().text = txt;
     }
     else
     {
            dialogueContainer.GetComponentInChildren<Text>().text = txt;
     }
}

Is there a better way to do this? Why can I select a field in the inspector, but I have to make the SetTextField method in order to create a listener through code? I’m quite new to Unity Events and can’t seem to formulate the search query correctly when trying to google this

The inspector does some magic to basically do what you are doing in the code. At runtime the AddListener method will only accept methods that match the signature of the event. How you have it setup is the only real way to set it up at runtime. It would be nice to be able to put fields into the AddListener method but UnityEvents are more setup for the editor, RemoveListener and RemoveAllListeners only works on listeners added at runtime, the ones applied in the editor are considered persistent and cannot be removed.

One thing I am a bit OCD about is the GetComponent calls, cache that in Start and avoid those expensive calls.

1 Like

@Chris-Trueman maybe future versions of Unity will allow putting fields at runtime :slight_smile:
Thank you for helping! And don’t worry, I’ll cache the “GetComponents”

1 Like