我試圖加載一個紋理,我編碼到一個jpeg,然後序列化/發送爲一個字節數組從客戶端到我的服務器,然後反序列化和應用紋理一個實例化的預製件。除了最後我試圖將紋理應用於我的預製件時,一切似乎都在起作用。我發現了錯誤:我如何使編程的紋理可讀
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)
我知道我可以在統一編輯本可讀的,但因爲我做這一切在運行時,我該如何做到這一點?
轉換紋理JPG
IEnumerator DoGetTexToBytes(Texture2D tex)
{
playerObj.texBytes = tex.EncodeToJPG(50);
yield return new WaitForEndOfFrame();
}
組裝所有選手對象數據爲字節陣列(包括紋理)
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));
}
發送字節,接收關於服務器,然後實例化一個預製與質地:
[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;
}
那麼我如何加載使用紋理編碼爲jpeg作爲編程上的預製紋理?我必須將我的紋理編碼爲jpg,以便我可以通過網絡快速發送它。 – greyBow
他從代碼中詢問,而不是編輯。 @greyBow查看重複 – Programmer
@programmer我查看了另一個線程,除非我遺漏了一些東西,它仍然沒有解釋如何獲取這個重複的紋理並將其編碼爲jpg以減小文件大小。我嘗試編碼在另一個線程創建腳本的新紋理,但我仍然有相同的錯誤是有任何其他方式編碼紋理JPEG,然後以編程方式讀回來? – greyBow