我试图加载一个纹理,我编码到一个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