- Home /
Texture2D GetPixel returns the same value everywhere
I am trying to calculate the exposed area of a falling Starship. For this, I am trying to use an orthographic camera that looks at and renders to a render texture. I want to count the pixels with the ship on it to calculate the area. I converted the render texture to a Texture2D and I am rendering that to on a RawImage, but when I want to use GetPixel() on any pixel it returns 205 or 0.8039216.
public Transform Ship;
public RawImage ri;
public RenderTexture area;
private Texture2D area2D;
void Start()
{
transform.position = new Vector3(Ship.position.x, 0f, Ship.position.z);
transform.LookAt(Ship);
}
void Update()
{
transform.position = new Vector3(Ship.position.x, 0f, Ship.position.z);
area2D = toTexture2D(area);
ri.texture = area2D;
Debug.Log(area2D.GetPixel(128,128).grayscale);
}
public Texture2D toTexture2D(RenderTexture rTex)
{
Texture2D dest = new Texture2D(rTex.width, rTex.height, TextureFormat.RGBA32, false);
Graphics.CopyTexture(rTex, dest);
return dest;
}
Answer by Bunny83 · Dec 04, 2021 at 02:19 PM
You can not use CopyTexture to read texture data from the GPU. See the last sentence on the CopyTexture page.:
CopyTexture operates on GPU-side data exclusively
As you may know a Texture2D may exist both in normal CPU memory (this is the case when the texture was loaded from disk) and also in GPU memory. Calling Apply will transfer / upload the image data from the CPU / system memory to the GPU. Textures also can only exist on the GPU side. This is the case when the texture marked as "not readable". This would free up the memory on the CPU side.
When you use CopyTexture you only copy the data on the GPU from one texture to the other. However you can not simply "download" the data from the GPU. For this you have to use Texture2D.ReadPixels.
Answer by mitohnesprudel · Dec 04, 2021 at 02:21 PM
This finally works
public Transform Ship;
public int widht, height;
public RenderTexture rt;
public int area;
void Start()
{
transform.position = new Vector3(Ship.position.x, 0f, Ship.position.z);
transform.LookAt(Ship);
}
void Update()
{
area = 0;
transform.position = new Vector3(Ship.position.x, 0f, Ship.position.z);
RenderTexture.active = rt;
Texture2D tex = new Texture2D(widht, height);
tex.ReadPixels(new Rect(0,0, tex.width, tex.height),0, 0);
tex.Apply();
for(var x = widht; x > 0; x--)
{
for(var y = height; y > 0; y--)
{
if(tex.GetPixel(x,y).grayscale > 0)
{
area++;
}
}
}
}
Your answer
Follow this Question
Related Questions
Get RenderTexture 1 Answer
Alternative for Graphics.CopyTexture() ? 2 Answers
Converting a RenderTexture to a Texture2D for use in a shader 2 Answers
ReadPixels returns RGBA(0,0,0,0) 0 Answers
Find a colour in a Texture2D 1 Answer