A Terraria tModLoader library mod that provides an easy solution for sending/receiving ModPackets
with custom data.
- tModLoader for
1.4.4
. Side = Both
inbuild.txt
(default if not specified).
- Add
modReferences = EasyPacketsLib
to your mod'sbuild.txt
file. - Add
EasyPacketsLib.dll
to your project as a reference (download from Releases). - Subscribe to the library mod on the Steam Workshop.
public readonly struct ExamplePacket : IEasyPacket<ExamplePacket>
{
public readonly int X;
public readonly int Y;
public ExamplePacket(int x, int y)
{
X = x;
Y = y;
}
void IEasyPacket<ExamplePacket>.Serialise(BinaryWriter writer)
{
writer.Write(X);
writer.Write(Y);
}
ExamplePacket IEasyPacket<ExamplePacket>.Deserialise(BinaryReader reader, in SenderInfo sender)
{
return new ExamplePacket(reader.ReadInt32(), reader.ReadInt32());
}
}
Serialise
: Serialise the packet data using the provided writer.Deserialise
: Deserialise the packet data using the provided reader.
Mod.SendPacket(new ExamplePacket(1, 2), toClient: -1, ignoreClient: -1, forward: false);
toClient
: If non-negative, the packet will only be sent to the specified client.ignoreClient
: If non-negative, the packet will not be sent to the specified client.forward
: If sending from a client, the packet will be forwarded to other clients through the server.
The packet can be received in two ways, both of which use the following parameters:
packet
: Packet data received.sender
: Information regarding the sender of the packet.handled
: An unhandled packet will raise an error.
public readonly struct ExamplePacketHandler : IEasyPacketHandler<ExamplePacket>
{
void IEasyPacketHandler<ExamplePacket>.Receive(in ExamplePacket packet, in SenderInfo sender, ref bool handled)
{
handled = true;
}
}
Any struct that implements the interface will be loaded automatically.
You are free to implement IEasyPacket<T>
and IEasyPacketHandler<T>
on the same type.
public override void Load()
{
Mod.AddPacketHandler<ExamplePacket>(OnExamplePacketReceived);
}
public override void Unload()
{
Mod.RemovePacketHandler<ExamplePacket>(OnExamplePacketReceived);
}
private void OnExamplePacketReceived(in ExamplePacket packet, in SenderInfo sender, ref bool handled)
{
handled = true;
}
Adding and removing handlers can occur at any time; it is not restricted to when the mod is loading/unloading.
In the above example (in ModSystem
), removing the handler can be omitted as this happens automatically when the mod unloads.
If you have any questions or would like to get in contact, shoot me an email at [email protected]
.
Alternatively, you can send me a direct message on Twitter at @DavidF_Dev.