- Home /
Setting a sprite's size with pixels
I am relatively new to C#, but I know my way around most of the basics. I know this question has been asked many times, and, after nearly 2 hours of searching I still can't seem to find an answer that works, so please bear with me.
I'm creating a 2D Unity game for iOS, and I need to be able to get the size of the screen, (I know how to do this, it is Screen.width / Screen.height) and with that, set the size of a sprite. I'm trying to get 7 sprites (width-wise) on the screen, but I need it to adjust with the device. Hard coding numbers won't do here. So, to achieve this, I need a way to scale by pixels, which I'm not sure how to do, or if it is even possible with Unity. If there is any other way, please let me know.
(Yes, I have tried using Rect and RectTransform, it either doesn't do what I need, or I'm using it wrong. could be either.)
Answer by revolute · Nov 15, 2019 at 02:55 AM
Use canvas scaler. The whole canvas is scaled to fit reference resolution. Depending on what you need, make it match width or height. After that, any sprite you put in your canvas will be "pixel" size.
@revolute I'm not sure I understand what you mean. $$anonymous$$ay you elaborate a little more please?
Answer by HelpMeGame · Nov 20, 2019 at 11:41 PM
I figured it out, I had to use a combination of math functions that determined the width of the screen, they I had to perfect some of the numbers from there.
Here is a general idea of what works:
//Declaration Of Variables
float blockSize = Screen.width / 8.75f;
float blockDistanceX = Screen.width / 8.75f;
void Start()
{
//Extra variables that couldn't be declared earlier
float xValue = blockDistanceX * -1f * 3.8f;
float layerPos = -1500;
//Creates new Block
GameObject block = Instantiate(objectPrefab, new Vector3(0, 0, 1), Quaternion.identity, parent: canvas);
block.transform.localScale = new Vector2(blockSize, blockSize);
block.transform.localPosition = new Vector2(xValue, layerPos);
}