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;
}