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;
    }

1 Answer

1

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.