- Home /
How to change the width of a Tiled sprite from script?
I'm making a Health Bar prefab (see screenshot). I use an image of a square that I repeat with Draw Mode set to Tiled to divide the bar into squares. I want enemies with more health to have longer bars with more squares. When I change the Width in the inspector, it works as expected (the bar appears longer or shorter and more squares are added or removed accordingly). However, when I change the width in code, nothing happens.
I tried setting SpriteRenderer.size but it doesn't do anything (the width and height of my SpriteRenderer don't change). The doc says Property to set/get the size to render when the SpriteRenderer.drawMode is set to SpriteDrawMode.Sliced.
and in my case, the Draw Mode is not set to Sliced. Even if I set the DrawMode to Sliced (which isn't what I want) it doesn't do anything either. So how do I change the width of my Tiled Sprite through code?
I can't use SpriteRenderer.transform.localScale because that would stretch the bar without adding more squares.
EDIT: The problem was that I was using mySpriteRenderer.size.Set(widht, height); I used mySpriteRenderer.size = new Vector2(width, height); instead and it worked.
Answer by xxmariofer · Jan 16, 2019 at 03:04 PM
Just did this simple script for making sure it workded and everything seems fine, Just create a SpriteRenderer object and copy that lines in start, then just play with the vector2 vars for adjusting it to you gameplay mechanic.
void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
spriteRenderer.drawMode = SpriteDrawMode.Tiled;
spriteRenderer.size = new Vector2(5,1);
}
Thank you, I was using mySpriteRenderer.size.Set(widht, height); I used mySpriteRenderer.size = new Vector2(width, height); ins$$anonymous$$d and it worked
Answer by tormentoarmagedoom · Jan 16, 2019 at 03:01 PM
Good day.
How do you try to change it?
Spriterenderer size is a Vector2 variable, you should be able to change it as the documentation says.
https://docs.unity3d.com/ScriptReference/SpriteRenderer-size.html
sprRend.size += new Vector2(0.05f, 0.01f);
or
sprRend.size = new Vector2(3, 1);
Bye!
Thank you, I was using mySpriteRenderer.size.Set(widht, height) I used mySpriteRenderer.size = new Vector2(width, height) ins$$anonymous$$d and it worked
Your answer
Follow this Question
Related Questions
White lines between adjacent/overlapping sprites and from tiled sprites? 0 Answers
hide animated Sprite by code (SpriteRenderer) 2 Answers
Script to change SpriteRenderers sprite field 2 Answers
Override sprite geometry of sprite generated at runtime 1 Answer
[Unity3D] Sprite not rendering correctly when it's too small? (Appearing like a blob) 0 Answers