简体   繁体   中英

How to send Texture2D over the Network in Unity?

So, I have a game, where players, have to draw on Texture2D and I need to send that Texture2D for other players, but onPhotonSerializeView isn't working for that, because Exception: cannot serialize(): UnityEngine.Texture2D .

I found this solution on site, but I don't really understand it, so maybe somebody could help.

My code:

private Texture2D DrawingSection;

private void Awake()
{
    DrawingSection = GameObject.Find("Canvas/pan_Background/pan_DrawingSection").GetComponent<Texture2D>();
}

private void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
    if (stream.isWriting)
    {
        if (photonView.isMine)
        {
           stream.SendNext(DrawingSection);
        }
    }
    else
    {
        DrawingSection = (Texture2D)stream.ReceiveNext();
    }
}

Since you cant send Texture2D , you will need to transform it into a byte[] by doing

var bytes = DrawingSection.EncodeToPNG();

and then send the bytes like

stream.SendNext(bytes);

When reading the bytes, you would receve a byte[]

var bytes = (byte[])stream.ReceiveNext();

Then you need to parse the byte[] into a the Texture2D

This should probably work, i assume both sides have the same TextureFormat and size?

DrawingSection.LoadImage(bytes);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM