Search code examples
c#user-interfaceunity-game-enginepositioning

Code to position instantiated UI prefab based on screen size?


I am struggling with this situation on how to position a instantiated prefab based on the screen size, my following code is this :=

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class UPStand : MonoBehaviour 
{

    public GameObject SaleButtonPrefab;
    public GameObject ParentButton;
    public int 

    void Start()
    {
        //To loop all the list
        for(int i = 0; i < 3; i++)
        {
            //Instantiate the button prefab and make a parent
            GameObject nu = Instantiate(SaleButtonPrefab) as GameObject;
            nu.transform.SetParent(ParentButton.transform, false);

            //To set the position and function
            nu.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, (i*-289.5f) );// <-- This positioning does not position with screen the size
        }
    }
}

when I run this on a resolution of 720x1280, it works perfectly as the image shows below:

enter image description here

But when I run this on a resolution lets say 900x1100, the positioning of the height is rather different as the image shows below:

enter image description here

I tried setting up the anchor position to the corners of the image, it works in terms of the scaling but not the positioning though, any ideas?

And thanks in advance c:


Solution

  • Select your canvas and in the inspector choose scale with screen size and put in the highest resolution you want for your game , always base your GUI on it and dont use free aspect in the game view always use the resolution you want to see , but still try changing changing the pivots manually by dragging them to the downward ends of your panel or to the bottom of the whole canvas that way only height will be changed.