Search code examples
c#unity-game-engineeventshandler

How do Unity Events for Video Players work?


We have a script attached to an object that has a VideoPlayer and some video. We want to know (be subscribed to) when the video ends, so we can decide then to play another or do something else.

void Start()
{
    videoPlayer.loopPointReached += Method();
}

VideoPlayer.EventHandler Method()
{
    Debug.Log("it ended");
    return null;
}

And the log is not coming out when the video ends.

The reference to videoPlayer exists, and the video plays, pauses and stops with no issues.

We find solutions that include counting frames and so on, but we're hoping for a more elegant solution.


Solution

  • Your code is written wrong. Actually this code is the same if you write videoPlayer.loopPointReached += null;. So you subscribe null for loopPointReached event. You messed up event handler delegate with its signature return type. Your code should look like this, I suppose:

    void Start()
    {
        videoPlayer.loopPointReached += Method; // do not call method with '()', but just subscribe it for event
    }
    
    // here the signature of the method corresponds to VideoPlayer.EventHandler delegate,
    // that is void(VideoPlayer)
    private void Method(VideoPlayer source)
    {
        Debug.Log("it ended");
    }
    

    You can check signature of this delegate in Unity docs https://docs.unity3d.com/2017.2/Documentation/ScriptReference/Video.VideoPlayer.EventHandler.html

    Also you can read move about events in this topic How to make a keypress form event in C#