如何以编程方式使纹理可读

时间:2017-11-04 00:05:33

标签: c# unity3d networking textures jpeg

我尝试将我编码的纹理加载到jpeg,然后作为字节数组从客户端序列化/发送到我的服务器,然后反序列化并将纹理应用于实例化的预制件。除了最后我试图将纹理应用到我的预制件时,一切似乎都在起作用。我收到了错误:

  

UnityException:纹理'鹿'不可读,无法从脚本访问纹理内存。您可以在纹理导入设置中使纹理可读。   Player_Data + c__Iterator0.MoveNext()(在Assets / _Scripts / Player / Player_Data.cs:82)   UnityEngine.SetupCoroutine.InvokeMoveNext(IEnumerator枚举器,IntPtr returnValueAddress)(在C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)   UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator的)   Player_Data:PrepareServerData(String)(在Assets / _Scripts / Player / Player_Data.cs:56)   PaintCraft.Controllers.c__Iterator2:MoveNext()(在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;
    }

1 个答案:

答案 0 :(得分:1)

您需要在图像的导入设置中设置读/写启用标志。

Settings

除非您正在编写编辑器脚本(仅在编辑器中运行,而不是在发布时),否则我认为您无法通过代码执行此操作。