有两种方法可以做到这一点:
1.Use RenderTexture
(受到推崇的):
Use RenderTexture
。把源码贴上来Texture2D
into RenderTexture
with Graphics.Blit
然后使用Texture2D.ReadPixels
从中读取图像RenderTexture
进入新的Texture2D
.
Texture2D duplicateTexture(Texture2D source)
{
RenderTexture renderTex = RenderTexture.GetTemporary(
source.width,
source.height,
0,
RenderTextureFormat.Default,
RenderTextureReadWrite.Linear);
Graphics.Blit(source, renderTex);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = renderTex;
Texture2D readableText = new Texture2D(source.width, source.height);
readableText.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
readableText.Apply();
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(renderTex);
return readableText;
}
Usage:
Texture2D copy = duplicateTexture(sourceTextFromPlugin);
这应该可以工作并且不会引发任何错误。
2.Use Texture2D.GetRawTextureData()
+ Texture2D.LoadRawTextureData()
:
你不能使用GetPixels32()
因为Texture2D
不可读。你非常接近使用GetRawTextureData()
.
你使用的时候失败了Texture2D.LoadImage()
加载自GetRawTextureData()
.
Texture2D.LoadImage()
is only用于加载PNG/JPG数组字节而不是Texture2D数组字节。
如果你阅读与Texture2D.GetRawTextureData()
,你必须写成Texture2D.LoadRawTextureData()
not Texture2D.LoadImage()
.
Texture2D duplicateTexture(Texture2D source)
{
byte[] pix = source.GetRawTextureData();
Texture2D readableText = new Texture2D(source.width, source.height, source.format, false);
readableText.LoadRawTextureData(pix);
readableText.Apply();
return readableText;
}
上面的代码在编辑器中不会有错误,但在独立构建中应该会出现错误。此外,即使独立构建中出现错误,它也应该仍然可以工作。我认为这个错误更像是一个警告。
我推荐你使用方法#1这样做,因为它不会引发任何错误。