2
\$\begingroup\$

I'm trying to:

  1. load texture from assets folder
  2. create a clone of said texture that will be manipulated during runtime
  3. set pixels on cloned texture

I have successfully set pixels on the original texture (ie. discarding the code in the start function), but I cannot seem to be able to draw to the duplicated version.


void Start () {

    canvas = gameObject.GetComponent(typeof(SpriteRenderer)) as SpriteRenderer;
    Sprite oldSprite = canvas.sprite;
    Texture2D oldTex = oldSprite.texture;
    Rect oldRect = oldSprite.textureRect;

    tex = new Texture2D(oldTex.width, oldTex.height, TextureFormat.RGB24, false);
    tex.SetPixels32(oldTex.GetPixels32());
    tex.Apply();

    Rect r = new Rect(oldRect.x, oldRect.y, oldRect.width, oldRect.height);
    Vector2 pivot = new Vector2(oldSprite.pivot.x, oldSprite.pivot.y);
    float pixelsPerUnit = oldSprite.pixelsPerUnit;
    Sprite sprite = Sprite.Create(tex, r, pivot, pixelsPerUnit, 0, SpriteMeshType.FullRect);

    canvas.sprite = sprite;
}

public void draw(Tool tool, Color32 color, List<Vector2> locations) {
    Color32[] pixels = tex.GetPixels32(0);

    for(int i = 0; i < pixels.Length; ++i) {
        pixels[i] = color;
    }
    tex.SetPixels32(pixels);
    tex.Apply();
}

Please ignore the unused vars, I'm just trying to set the whole texture's color for now.

Anyways, any help is always appreciated - thanks :)

\$\endgroup\$
2
  • \$\begingroup\$ Does it make any difference if you define your new texture as ARGB32 or RGBA32 instead of RGB24? I've found sometimes other formats are more picky about dynamic writes. \$\endgroup\$
    – DMGregory
    Nov 17, 2017 at 13:00
  • \$\begingroup\$ Just tried it now, unforunately didn't help - nothing changed. Thanks though \$\endgroup\$
    – annon
    Nov 18, 2017 at 19:18

1 Answer 1

0
\$\begingroup\$

The problem was this line:

Vector2 pivot = new Vector2(oldSprite.pivot.x, oldSprite.pivot.y);

oldSprite.pivot.x returns a pixel coordinate and I was expecting it to be a float between 0.0f and 1.0f. Once the args were changed, drawing on the texture worked perfectly fine.

revised:

Vector2 pivot = new Vector2(0.5f, 0.5f);
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .