I'm trying to load a texture that I'm encoding to a jpeg and then serializing/sending as a byte array from a client to my server and then deserializing and applying the texture to an instantiated prefab. Everything seems to be working except at the end when I'm trying to apply the texture to my prefab. I'm getting the error:
UnityException: Texture 'deer' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings. Player_Data+c__Iterator0.MoveNext () (at Assets/_Scripts/Player/Player_Data.cs:82) UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17) UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator) Player_Data:PrepareServerData(String) (at Assets/_Scripts/Player/Player_Data.cs:56) PaintCraft.Controllers.c__Iterator2:MoveNext() (at Assets/_Scripts/ColoringBook/CanvasController.cs:221)
I know that I can make this readable in the unity editor, but since I'm doing all of this at runtime, how do I accomplish this?
convert texture to jpg
IEnumerator DoGetTexToBytes(Texture2D tex)
{
playerObj.texBytes = tex.EncodeToJPG(50);
yield return new WaitForEndOfFrame();
}
assemble all player object data into byte array (including texture)
public void PrepareServerData(Texture2D texToSend, string typeToSend)
{
StartCoroutine(DoGetTexToBytes(texToSend));
playerObj.texWidth = texToSend.width;
playerObj.texHeight = texToSend.height;
playerObj.texFormat = texToSend.format;
playerObj.tranX = tran.x;
playerObj.tranY = tran.y;
playerObj.tranZ = tran.z;
playerObj.type = typeToSend;
Player_ID id = GetComponent<Player_ID>();
playerObj.id = id.MakeUniqueIdentity();
playerObj.strength = strengthToSend;
playerObj.hitpoints = hitPointsToSend;
Network_Serializer serialize = GetComponent<Network_Serializer>();
// Send Data from Client to Server as many small sequenced packets
byte[] bytes = serialize.ObjectToByteArray(playerObj);
StartCoroutine(Network_Transmitter.instance.DoSendBytes(0, bytes));
}
send bytes, receive on server and then instantiate a prefab with the texture:
[Server]
public void InstantiatePlayerOnServer(PlayerObject playerObj)
{
GameObject go = Instantiate(Player_Controller.instance.serverAvatar, new Vector3(playerObj.tranX, playerObj.tranY, playerObj.tranZ), Quaternion.identity) as GameObject;
// go.transform.parent = GameObject.FindGameObjectWithTag("Player").transform;
StartCoroutine(DoLoadRawTextureData(go, playerObj.texBytes, playerObj.texWidth, playerObj.texHeight, playerObj.texFormat));
}
[Server]
IEnumerator DoLoadRawTextureData(GameObject go, byte[] texBytes, int texWidth, int texHeight, TextureFormat texFormat)
{
Texture2D tex = new Texture2D(texWidth, texHeight, texFormat, false);
tex.LoadRawTextureData(texBytes);
tex.Apply();
yield return new WaitForEndOfFrame();
go.GetComponent<Renderer>().material.mainTexture = tex;
}