Search code examples
minecraft-fabric

I don't understand, how can I listen to events in FabricMC (1.20)


I'm new to mod developement, tried it firstly today. I want to make event, that will trigger when player joins a singleplayer or multiplayer world. How can I do this?

Also, I'm really sorry for wasting your time if its a dumb question.

Tried to search in Google, and find nothing...


Solution

  • Correct me if I'm wrong, but it sounds like you want to register an event handler rather than create a new event.

    I'm unsure if you want your event handler to trigger client-side or server-side, so I will provide examples for both.

    Note that the server-side event will be triggered on the dedicated server when joining a multiplayer world, and on the client's integrated server when joining a singleplayer world. See this page of the Fabric Wiki for more details on that.

    Client-side

    import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
    
    // put this in your mod initializer method
    ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> {
        // get the player
        var player = client.player;
        // handle the event here...
    });
    

    Server-side

    import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
    
    // put this in your mod initializer method
    ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
        // get the player
        var player = handler.player;
        // handle the event here...
    });