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

Resolved Changing a sprite with custom image changes the position of the gameObject

Discussion in '2D' started by Rakanacazacateca, Mar 30, 2023.

  1. Rakanacazacateca

    Rakanacazacateca

    Joined:
    Sep 29, 2021
    Posts:
    4
    I was making a photoshop-like app with the option to change the background image of the canvas, but doing so also seems to change the canvas position, I searched for a while but found no info

    This is the code for tghe change of sprite I used

    The activeLayer is the current canvas.

    Code (CSharp):
    1. public void ChangeBackground(Texture2D image)
    2.     {
    3.         Rect rect = new Rect(0, 0, image.width, image.height);
    4.         SpriteRenderer activeLayer = myLayer.GetComponent<SpriteRenderer>();
    5.         Sprite background = Sprite.Create(image, rect, myLayer.transform.position);
    6.         activeLayer.sprite = background;
    7.     }
     

    Attached Files:

  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    Check the pivot on the sprite in the texture import panel (Inspector when texture is selected).
     
  3. Rakanacazacateca

    Rakanacazacateca

    Joined:
    Sep 29, 2021
    Posts:
    4
    They stay the same, and both textures have the saame width & height
     

    Attached Files:

    • 1.png
      1.png
      File size:
      104.7 KB
      Views:
      68
    • 2.png
      2.png
      File size:
      341.4 KB
      Views:
      69
  4. karderos

    karderos

    Joined:
    Mar 28, 2023
    Posts:
    376
    you are using sprite.create incorrectly to set the pivot, you should not place the transform in there
     
    Rakanacazacateca and Kurt-Dekker like this.
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    Oooo... very nice spot kard!

    Yeah, those pivot values should be 0 to 1 if you want them to be within the bounds of the sprite. Go check the docs.
     
    Rakanacazacateca likes this.
  6. Rakanacazacateca

    Rakanacazacateca

    Joined:
    Sep 29, 2021
    Posts:
    4
    Thanks Kard and Kurt, that solved the problem, changed the script this way

    Code (CSharp):
    1. public void ChangeBackground(Texture2D image)
    2.     {
    3.         Rect rect = new Rect(0, 0, image.width, image.height);
    4.         SpriteRenderer activeLayer = myLayer.GetComponent<SpriteRenderer>();
    5.         Sprite background = Sprite.Create(image, rect, new Vector2(0.5f, 0.5f));
    6.         activeLayer.sprite = background;
    7.     }
    Putting 0, 0 to the pivot gave me the same problem, I tried 0.5, 0.5 and worked.
     
    Kurt-Dekker likes this.