๐ŸพPurrNet Docs
Advanced

BitPacker Serialization

BitPacker is PurrNet's low-level binary serializer. It writes data bit-by-bit, letting you pack integers into the minimum number of bits they need and quantize floats to save bandwidth on custom network types.

An integer in range 0โ€“500 only needs 9 bits. Without BitPacker the full 32-bit int is sent.

Without BitPacker
int (32 bits)
32 bits used
With BitPacker
9 bits (2โน = 512 โ‰ฅ 500)
9 bits used
23 bits savedยท72% smaller
C# โ€” Pack method
packer.PackInt(ref damage, 0, 500);  // 9 bits

Two serialization modes

PurrNet supports two interfaces for custom type serialization, suited to different use cases:

ParameterTypeDefaultDescription
IPackedAutointerfaceโ€”Marker interface โ€” PurrNet automatically serializes all public fields using reflection. Zero boilerplate. Best for simple, flat structs.
IPackedinterfaceโ€”Manual serialization interface. Implement Pack(BitPacker) and Unpack(BitPacker) for full control โ€” use quantized floats, delta encoding, and bit flags.
[RegisterNetworkType(typeof(T))]attributeโ€”Required on any custom struct or class used in SyncVars or RPC parameters. Registers the type with PurrNet's serializer at startup.

BitPacker methods

ParameterTypeDefaultDescription
PackInt(ref int value, int min, int max)voidโ€”Pack an integer using the minimum number of bits required to represent the [min, max] range. Dramatically reduces bandwidth for small-range integers.
PackFloat(ref float value, float min, float max, int bits)voidโ€”Quantize a float to a fixed bit count within [min, max]. E.g. 8 bits gives 256 steps across the range.
PackBool(ref bool value)voidโ€”Pack a boolean as a single bit.
PackString(ref string value)voidโ€”Pack a UTF-8 string with a compact length prefix.
PackBytes(ref byte[] value)voidโ€”Pack a raw byte array with a compact length prefix.
PackEnum<T>(ref T value)voidโ€”Pack an enum using only the bits needed to represent its declared values.

IPackedAuto โ€” simple structs

For data that has no special packing requirements, implement IPackedAuto and annotate the type with [RegisterNetworkType]. PurrNet reflects over all public fields and serializes them automatically.

PlayerState.cs
using PurrNet;
using UnityEngine;

// IPackedAuto: PurrNet serializes all public fields automatically
[RegisterNetworkType(typeof(PlayerState))]
public struct PlayerState : IPackedAuto
{
    public Vector3 position;
    public float   health;
    public int     score;
    public string  displayName;
    public bool    isAlive;
}

// Use in a SyncVar like any built-in type
public class PlayerStats : NetworkBehaviour
{
    private SyncVar<PlayerState> _state = new(new PlayerState
    {
        health = 100f,
        isAlive = true,
        displayName = "Player",
    });

    public void UpdateState(Vector3 pos, float hp)
    {
        if (!isServer) return;
        _state.value = new PlayerState
        {
            position    = pos,
            health      = hp,
            score       = _state.value.score,
            displayName = _state.value.displayName,
            isAlive     = hp > 0f,
        };
    }
}

IPacked โ€” manual control with delta compression

When bandwidth matters, implement IPackedand hand-write the Pack/Unpack methods. This lets you quantize floats (e.g. pack an angle as 8 bits instead of 32), combine booleans into a single bit field, or omit fields that haven't changed.

DamagePacket.cs
using PurrNet;
using UnityEngine;

// IPacked: full manual control โ€” every bit counts
[RegisterNetworkType(typeof(DamagePacket))]
public struct DamagePacket : IPacked
{
    // Damage 0โ€“500 needs 9 bits (vs 32 for int)
    public int     damage;

    // Direction as two quantized floats โ€” 8 bits each instead of 96
    public Vector3 hitDirection;

    // Bit flags for hit type โ€” 1 bit each
    public bool isCritical;
    public bool isPenetrating;
    public bool isHeadshot;

    // Hit location enum โ€” only 4 values, needs 2 bits
    public HitLocation location;

    public void Pack(BitPacker packer)
    {
        packer.PackInt(ref damage, 0, 500);                   // 9 bits
        float dx = hitDirection.x, dy = hitDirection.y, dz = hitDirection.z;
        packer.PackFloat(ref dx, -1f, 1f, 8);                // 8 bits
        packer.PackFloat(ref dy, -1f, 1f, 8);                // 8 bits
        packer.PackFloat(ref dz, -1f, 1f, 8);                // 8 bits
        hitDirection = new Vector3(dx, dy, dz);

        packer.PackBool(ref isCritical);                      // 1 bit
        packer.PackBool(ref isPenetrating);                   // 1 bit
        packer.PackBool(ref isHeadshot);                      // 1 bit
        packer.PackEnum(ref location);                        // 2 bits
        // Total: ~46 bits vs 160 bits with IPackedAuto โ€” 71% smaller
    }

    public void Unpack(BitPacker packer)
    {
        // Unpack in the same order as Pack
        Pack(packer);
    }
}

public enum HitLocation { Body, Head, Limb, Shield }

Packing multiple booleans as bit flags

A struct with eight booleans using IPackedAuto costs 8 bytes. With manual packing, all eight fit in a single byte:

StatusFlags.cs
using PurrNet;

[RegisterNetworkType(typeof(StatusFlags))]
public struct StatusFlags : IPacked
{
    public bool isBurning;
    public bool isPoisoned;
    public bool isStunned;
    public bool isRooted;
    public bool isInvisible;
    public bool isShielded;
    public bool isHasted;
    public bool isSlowed;

    public void Pack(BitPacker packer)
    {
        // Each PackBool writes exactly 1 bit โ€” 8 booleans = 1 byte total
        packer.PackBool(ref isBurning);
        packer.PackBool(ref isPoisoned);
        packer.PackBool(ref isStunned);
        packer.PackBool(ref isRooted);
        packer.PackBool(ref isInvisible);
        packer.PackBool(ref isShielded);
        packer.PackBool(ref isHasted);
        packer.PackBool(ref isSlowed);
    }

    public void Unpack(BitPacker packer) => Pack(packer);
}

// Usage in a NetworkBehaviour
public class StatusEffects : NetworkBehaviour
{
    private SyncVar<StatusFlags> _flags = new(default);

    public void ApplyBurn()
    {
        if (!isServer) return;
        var f = _flags.value;
        f.isBurning = true;
        _flags.value = f;
    }
}

Use IPackedAuto for simple structs

Unless you have a specific bandwidth requirement, start with IPackedAuto. It requires zero boilerplate and handles all primitive types, Vector3, Quaternion, string, and enums automatically. Migrate to IPacked only when profiling shows the struct is on a hot send path.

Struct layout changes break compatibility

If you change the field order or add/remove fields on an IPackedAuto struct, old clients will misread the data and potentially crash. When shipping updates, version your packets: add a version field at the front, or use a new type name, to maintain backward compatibility during rolling deploys.