Beginner SpriteRenderer Sprite Size Scaling Question

Hi there,

I have the following problem: For my UI-buttons, I use GameObjects that have both, an image (as a general grid) and SpriteRenderer (as indicator for the specific button), attached. All my buttons use the same image, but vary in the sprite that is used for the SpriteRenderer.

In the following code, I use the “weaponSwitchButton” as a prefab that contains both components and set the sprite of that button equal to the sprite of GameObject “weaponToAdd” (which is the weapon the button is created for). The problem is that the sprite is tiny compared to the respective image.

I know that I could fix this problem by manually setting sprites for each weapons and set their PixelsToUnit values to match the image, but I want to prevent duplicating all my sprites. Is there a way to set the sprites PixelsToUnits values via script? Or is there a better solution in general?

public void AddSwitchButton(GameObject weaponToAdd) // adds a button that allows weapon switching
    {
        GameObject toInstantiate = (GameObject)Instantiate(weaponSwitchButton); // creates the button
        toInstantiate.transform.SetParent(GameObject.Find("WeaponSelectGrid").transform,false); // sets the weapon select grid as the parent

        SpriteRenderer spriteRenderer = toInstantiate.GetComponent<SpriteRenderer>(); // sets the sprite of the button
        spriteRenderer.sprite = weaponToAdd.GetComponent<SpriteRenderer>().sprite;
}

If your button is using Unity UI (e.g. canvases and RectTransforms), then your in-button image should be an Image component, not SpriteRenderer. The good news is that Image uses the same Sprite to hold its graphic data, so you shouldn’t have to change much.

The problem is that my UI-button holds both, an image-component, as well as an SpriteRenderer-component since my visual representation of the button needs both. I use the image-component as the basic panel (which is also a sprite) and the sprite as the visual effect to distinguish between different “change weapon” buttons.
Is there a better way to do that?

The SpriteRenderer is not intended to be used within the UI system at all (I’m surprised it shows up at all, honestly). Just make a second Image for the visual effect as a child object of the basic panel.

1 Like