Dan*_*Lip 2 c# unity-game-engine
我不明白这个异常以及如何修复它。
例外情况在第 38 行:
pixels = origTex.GetPixels();
Run Code Online (Sandbox Code Playgroud)
完整的异常消息:
UnityException:纹理“screen_1920x1080_2021-07-09_14-08-00”不可读,无法从脚本访问纹理内存。您可以在纹理导入设置中使纹理可读。
我不知道如何处理。在此之前,这是我第一次遇到此异常。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RawImagePixelsChange : MonoBehaviour
{
// Create a blank RawImage and drag this script onto it
// NOTE: Unless you create a new texture from the image (instead of using it directly),
// changes will alter the asset itself!
// Textures must be type 2D/UI and have Read/Write enabled
// Unity docs say GetPixels32 etc. is faster, but I wasn't able to get the modifyPixels() to work...
// colors kept wrapping around 255, even with clamps (?)
RawImage myImage; // texture will be assigned in code, but can assign in Inspector to see in Editor
public Texture2D origTex; // drag texture to slot in Inspector
public Texture2D newTex; // leave blank, will be created in code
public float lightenAmount = 0.1f;
Color[] pixels;
void Start()
{
var texture = GetComponent<RawImage>().texture;
origTex = texture as Texture2D;
myImage = GetComponent<RawImage>();
// Prints the float equivalent color at pixel (50,50). Note the texture origin is lower left!
//print("pixel 50, 50 = " + origTex.GetPixel(50, 50));
if (texture != null && origTex != null)
{
pixels = origTex.GetPixels();
newTex = new Texture2D(origTex.width, origTex.height);
newTex.SetPixels(pixels);
newTex.Apply();
myImage.texture = newTex;
}
}
public void modifyPixels(float lightenAmount) // Press "P" to change pixel colors by lightenAmount
{
for (int i = 0; i < pixels.Length; i++)
{
pixels[i].r += lightenAmount;
if (pixels[i].r > 1) pixels[i].r = 1;
if (pixels[i].r < 0) pixels[i].r = 0;
pixels[i].g += lightenAmount;
if (pixels[i].g > 1) pixels[i].g = 1;
if (pixels[i].g < 0) pixels[i].g = 0;
pixels[i].b += lightenAmount;
if (pixels[i].b > 1) pixels[i].b = 1;
if (pixels[i].b < 0) pixels[i].b = 0;
}
newTex.SetPixels(pixels);
newTex.Apply();
}
public void restorePixels() // Press "O" (letter O) to restore original texture/image
{
pixels = origTex.GetPixels();
newTex.SetPixels(pixels);
newTex.Apply();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
modifyPixels(lightenAmount);
}
if (Input.GetKeyDown(KeyCode.O))
{
restorePixels();
}
}
public float Amount()
{
return lightenAmount;
}
}
Run Code Online (Sandbox Code Playgroud)