Search Unity

After using Texture2D.SetPixel and Apply, can't reset texture using SetTexture

Discussion in 'General Graphics' started by Predulus, Feb 5, 2018.

  1. Predulus

    Predulus

    Joined:
    Feb 5, 2018
    Posts:
    90
    First I am storing a texture in a global variable, in Start():

    private Texture2D tex1;
    tex1 = (Texture2D)GameObject.Find("plane1").GetComponent<Renderer>().material.GetTexture("_MainTex");

    Then I execute some code like this to apply a border to the texture, when a key is pressed:

    var borderColor = new Color(1, 0, 0, 1);
    for (int x = 0; x < image.width; x++) {
    for (int y = 0; y < image.height; y++) {
    if (x < borderWidth || x > image.width - 1 - borderWidth) image.SetPixel(x, y, borderColor);
    else if (y < borderWidth || y > image.height - 1 - borderWidth) image.SetPixel(x, y, borderColor);
    }
    }
    image.Apply();

    That code works.

    Then later, upon a different keypress, I try to load the original texture back again with:

    GameObject.Find("plane1").GetComponent<Renderer>().material.SetTexture("_MainTex", tex1);

    This doesn't work.

    Please help if you have some clue why. I've been googling, trying things, rinsing-and-repeating for hours now. Going a litle crazy.
     
  2. nygren

    nygren

    Joined:
    Feb 13, 2014
    Posts:
    33