- Home /
How to pass UnityEvent object as method Parameter
I'm building a tutorial system that has multiple steps. Each step has a certain event trigger, such as clicking on a button or completing the build of a structure. For simplicity sake, let's say I have the following code:
public class GameController : MonoBehaviour {
public UnityEvent gcEvent;
public TutorialManager tm = new TutorialManager();
void Start() {
tm.SetupTutorial(gcEvent);
}
}
public class TutorialManager {
public UnityEvent tmEvent;
public void SetupTutorial (UnityEvent passedEvent) {
tmEvent = passedEvent;
NextStep();
}
public void NextStep () {
tmEvent.AddListener(NextStep);
}
}
In this case, passedEvent is always null instead of the UnityEvent object (because it's passing by value instead of reference?). Therefore, tmEvent is also null, and referring to tmEvent in NextStep() returns an error.
How can I pass UnityEvents between classes like this? This is driving me crazy....
Looks to me like a bunch of empty variables. Where are you expecting the data to come from?
The example in the docs shows you do not create a 'new' UnityEvent, you should Add the Listener in Start and most certainly not within the function it is linking.
Here's the page
http://docs.unity3d.com/ScriptReference/Events.UnityEvent.html
Your code sample does not throw any errors. This extension:
public void SetupTutorial(UnityEvent passedEvent) {
tmEvent = passedEvent;
NextStep();
Debug.Log("invoking");
tmEvent.Invoke();
}
public void NextStep() {
Debug.Log("calling next step");
tmEvent.AddListener(NextStep);
}
Prints: "calling next step" "invoking" "calling next step"
You can pass UnityEvents around as if they were any other object. Do you have a failing example?
@meat, I'm assu$$anonymous$$g the event is assigned in the editor.
Why your GameController
class doesn't derive from $$anonymous$$onoBehaviour
? Then how do you expect the Start()
method in it to run?
It does in my actual code, sorry I didn't put it in my simplified code above!
So…it seems I have been duped by the $$anonymous$$onoDevelop debugger! One of the things I tried before posting this question was, as @meat5000 suggested, initialize gcEvent variable in the Start() method using “new UnityEvent();”. However, when I did this and stepped through the code, the debugger suggested in red “Object reference not set to an instance of an object” so I immediately reverted back to not initializing the variable (avoid red messages at all costs!).
That error message is somewhat incorrect/misleading apparently, as the event is actually working fine within my code now that I added back in the initialization statement. I guess they don’t consider a UnityEvent an object since it is a form of delegate?
Either way, thanks for the quick responses to the issue @meat5000 @Baste and @ben.rasooli !