Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Problem with SetPixel in a sprite

Discussion in 'Scripting' started by Fluzing, Aug 31, 2014.

  1. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    Hi All,

    I am trying to change the texture of a sprite with SetPixel. It works, but the problem is that the changes are persistent. If I stop the game, the texture stays changed.

    This is my code:

    Code (csharp):
    1.  
    2. void Start()
    3. {
    4.        //create a copy of the original sprite and set it to the sprite
    5.        Sprite temp_sprite = Instantiate(gameObject.GetComponent<SpriteRenderer> ().sprite) as Sprite;
    6.        gameObject.GetComponent<SpriteRenderer> ().sprite = temp_sprite;
    7.  
    8.        //draw the pixels
    9.         int y = 0;
    10.         while (y < temp_sprite.texture.height)
    11.         {
    12.             int x = 0;
    13.             while (x < 10) {
    14.                 Color color = Color.blue;
    15.                 temp_sprite.texture.SetPixel(x, y, color);
    16.                 ++x;
    17.             }
    18.             y++;
    19.         }
    20.         //apply the texture to the sprite
    21.         temp_sprite.texture.Apply();
    22. }
    23.  
    I have no idea why it does not work. Am I making a mistake in the copy somewhere?
     
  2. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    shameless bump

    Edit:

    Never mind. Solved with Sprite.Create
     
    Last edited: Sep 1, 2014
  3. davidsvson

    davidsvson

    Joined:
    Jul 4, 2014
    Posts:
    11
    Had this problem also, I too fixed it with Sprite.Create but would still like to know what's wrong.