Search Unity

  1. Calling all beginners! Join the FPS Beginners Mods Challenge until December 13.
    Dismiss Notice
  2. It's Cyber Week at the Asset Store!
    Dismiss Notice

Creating new Texture2D, size

Discussion in 'Scripting' started by kittik, Sep 15, 2018.

  1. kittik

    kittik

    Joined:
    Mar 6, 2015
    Posts:
    483
    I am creating a function that inverts black/white pictures pixels from either black to white, or white to black. In a slightly different piece of working code, I can convert white pixels to a color generated by perlin noise.

    In this instance however, I am getting an error that the dimension of newTex is 0x0. I thought however, that I had created the texture with a width and height value. The line producing an error is line 27. mapPixels is declared on line 7, while newTex is defined on line 9.

    The error report reads -
    Texture '' is degenerate (dimensions 0x0)
    UnityEngine.Texture2D:SetPixels(Color[])


    Code (CSharp):
    1.  public void InvertPixelColors()
    2.     {
    3.         int wid = pf.totalPixelsSquared;
    4.         int hei = wid;
    5.  
    6.         Texture2D mapTex = (Texture2D)pixelMask.GetComponent<Renderer>().material.mainTexture;
    7.         Texture2D newTex = new Texture2D(wid, hei);
    8.  
    9.         Color[] mapPixels = new Color[wid * hei];
    10.  
    11.         for (int h = 0; h < hei; h++)
    12.         {
    13.             for (int w = 0; w < wid; w++)
    14.             {
    15.                 Color pixColor = mapTex.GetPixel(w, h);
    16.                 if (IsWhite(pixColor))
    17.                 {
    18.                     mapPixels[w * h] = new Color(0, 0, 0);
    19.                 }
    20.                 else
    21.                 {
    22.                     mapPixels[w * h] = new Color(1, 1, 1);
    23.                 }
    24.             }
    25.         }
    26.  
    27.         newTex.SetPixels(mapPixels);
    28.         mapTex = newTex;
    29.         mapTex.Apply();
    30.     }

    I would appriciate any feedback, I can't see what's going wrong here. Thank you.
     
    Last edited: Sep 15, 2018
  2. kittik

    kittik

    Joined:
    Mar 6, 2015
    Posts:
    483
    By changing Texture2D newTex = new Texture2D(wid, hei); to Texture2D newTex = mapTex; the error is resolved. However, now I have an issue, where the mapPixels array length is 0.

    Could anyone enlighten me on why the mapPixels array has this length? I am trying to give it the length of wid * hei.

    Thanks.
     
  3. kittik

    kittik

    Joined:
    Mar 6, 2015
    Posts:
    483
    I have resolved the problem. I was calling the function at the wrong time. The function works when it is called at a particular point in the procedure I am making.