From 298435001afe407c8ec76bc4268f0cb1caff4f96 Mon Sep 17 00:00:00 2001 From: vis2k Date: Fri, 29 Apr 2022 10:08:33 +0800 Subject: [PATCH] fix: #3144 Reader/Writer Sprite null support & test to guarantee it never happens again --- Assets/Mirror/Runtime/NetworkReaderExtensions.cs | 8 +++++++- Assets/Mirror/Runtime/NetworkWriterExtensions.cs | 9 +++++++++ Assets/Mirror/Tests/Editor/NetworkWriterTest.cs | 14 ++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/Assets/Mirror/Runtime/NetworkReaderExtensions.cs b/Assets/Mirror/Runtime/NetworkReaderExtensions.cs index 6a3d29c8b..7140155a1 100644 --- a/Assets/Mirror/Runtime/NetworkReaderExtensions.cs +++ b/Assets/Mirror/Runtime/NetworkReaderExtensions.cs @@ -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()); } } } diff --git a/Assets/Mirror/Runtime/NetworkWriterExtensions.cs b/Assets/Mirror/Runtime/NetworkWriterExtensions.cs index 340cd13e0..9810a6efb 100644 --- a/Assets/Mirror/Runtime/NetworkWriterExtensions.cs +++ b/Assets/Mirror/Runtime/NetworkWriterExtensions.cs @@ -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); diff --git a/Assets/Mirror/Tests/Editor/NetworkWriterTest.cs b/Assets/Mirror/Tests/Editor/NetworkWriterTest.cs index c8e9ce189..86e0d580a 100644 --- a/Assets/Mirror/Tests/Editor/NetworkWriterTest.cs +++ b/Assets/Mirror/Tests/Editor/NetworkWriterTest.cs @@ -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); + } } }