How do you use the network reader and writer?

I just tried it out but the result gives me 0 when i debug log.

How do you actually write and read the stream?

This is what i did to test:

    void Awake()
    {
        using (var stream = PooledNetworkBuffer.Get())
        {
            using (var writer = PooledNetworkWriter.Get(stream))
            {
                writer.SetStream(stream);
                writer.WriteBits((byte)2,3);
                writer.WriteBits((byte)5,3);
            }
            // test read
            using (var reader = PooledNetworkReader.Get(stream))
            {
                reader.SetStream(stream);
                ulong result = reader.ReadBits(3);
                Debug.Log(result); // should be 2, getting 0
                result = reader.ReadBits(3);
                Debug.Log(result); // should be 5, getting 0
            }
        }
    }

Am i missing something here?

You need to reset the streams position back to 0 after writing (before you read): stream.Position = 0;

Also the SetStream calls are not necessary the .Get method already does that.

Thanks that fixed it.

I did not know the .Get also sets the stream (that wasn’t obvious from the docs).

I tried to look for some thing like stream.ResetPosition() but could not find it. Did not realise it is done by property ( i think its more understandable if it used a method to reset versus assigning to the property).

Perhaps even better would be that when you do PooledNetworkReader.Get(stream) it will set the position at 0 by default…since 9 times out of 10 you probably will wish to start at 0.

Thanks for the help any way - it works now.

1 Like