Search Unity

Resolved How do you use the network reader and writer?

Discussion in 'Netcode for GameObjects' started by TheCelt, Sep 13, 2021.

  1. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    742
    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:

    Code (CSharp):
    1.     void Awake()
    2.     {
    3.         using (var stream = PooledNetworkBuffer.Get())
    4.         {
    5.             using (var writer = PooledNetworkWriter.Get(stream))
    6.             {
    7.                 writer.SetStream(stream);
    8.                 writer.WriteBits((byte)2,3);
    9.                 writer.WriteBits((byte)5,3);
    10.             }
    11.             // test read
    12.             using (var reader = PooledNetworkReader.Get(stream))
    13.             {
    14.                 reader.SetStream(stream);
    15.                 ulong result = reader.ReadBits(3);
    16.                 Debug.Log(result); // should be 2, getting 0
    17.                 result = reader.ReadBits(3);
    18.                 Debug.Log(result); // should be 5, getting 0
    19.             }
    20.         }
    21.     }

    Am i missing something here?
     
  2. luke-unity

    luke-unity

    Joined:
    Sep 30, 2020
    Posts:
    306
    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.
     
  3. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    742
    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.
     
    Sneirox likes this.