fix: #3144 Reader/Writer Sprite null support & test to guarantee it never happens again

This commit is contained in:
vis2k 2022-04-29 10:08:33 +08:00
parent f413c91cde
commit 298435001a
3 changed files with 30 additions and 1 deletions

View File

@ -292,7 +292,13 @@ public static Texture2D ReadTexture2D(this NetworkReader reader)
public static Sprite ReadSprite(this NetworkReader reader)
{
return Sprite.Create(reader.ReadTexture2D(), reader.ReadRect(), reader.ReadVector2());
// support 'null' textures for [SyncVar]s etc.
// https://github.com/vis2k/Mirror/issues/3144
Texture2D texture = reader.ReadTexture2D();
if (texture == null) return null;
// otherwise create a valid sprite
return Sprite.Create(texture, reader.ReadRect(), reader.ReadVector2());
}
}
}

View File

@ -312,6 +312,15 @@ public static void WriteTexture2D(this NetworkWriter writer, Texture2D texture2D
public static void WriteSprite(this NetworkWriter writer, Sprite sprite)
{
// support 'null' textures for [SyncVar]s etc.
// https://github.com/vis2k/Mirror/issues/3144
// simply send a 'null' for texture content.
if (sprite == null)
{
writer.WriteTexture2D(null);
return;
}
writer.WriteTexture2D(sprite.texture);
writer.WriteRect(sprite.rect);
writer.WriteVector2(sprite.pivot);

View File

@ -1520,5 +1520,19 @@ public void WriteSprite_normal()
Assert.That(sprite.texture.height, Is.EqualTo(example.texture.height));
Assert.That(sprite.texture.GetPixels32().SequenceEqual(example.texture.GetPixels32()));
}
// test to prevent https://github.com/vis2k/Mirror/issues/3144
[Test]
public void WriteSprite_Null()
{
// write
NetworkWriter writer = new NetworkWriter();
writer.WriteSprite(null);
// read
NetworkReader reader = new NetworkReader(writer.ToArray());
Sprite sprite = reader.ReadSprite();
Assert.That(sprite, Is.Null);
}
}
}