- Home /
Instantiating a UI element Screen.height and Screen.width way off
I am trying to instantiate a UI element that represents a player and their score.
When I use Screen.height
even when I scaled it based on the parent canvas with Vector2 panelBounds = (new Vector2(Screen.width, Screen.height) * mainCanvas.scaleFactor);
This is my main block that instantiates the UI element based on the bounds of the screen
public void AddPlayer()
{
Vector2 targetPos;
//Defining the screen bounds and accounting for the canvas scaleFactor
Vector2 panelBounds = (new Vector2(Screen.width, Screen.height) * mainCanvas.scaleFactor);
//Instantiating the UI element as a NameTag component
NameTag localTag = Instantiate(nameTag, new Vector3(0.0f, -panelBounds.y, 0.0f), transform.rotation).GetComponent<NameTag>();
localTag.transform.SetParent(container.transform, false);
//Sets the name and teh score as placeholders
localTag.Initalize(name, Random.Range(0, 100));
//Gets the size of the UI element that was instantiated
RectTransform tagRect = localTag.GetRectTransform();
Vector2 tagSize = tagRect.sizeDelta * mainCanvas.scaleFactor;
//Sets the target position to the top of the screen
targetPos = new Vector2(0.0f, panelBounds.y + tagSize.y / 2);
localTag.MoveToPos(targetPos);
}
public void MoveToPos(Vector2 target)
{
this.target = target;
StartCoroutine(Move(timeToArrive));
}
private IEnumerator Move(float time)
{
var elapsedTime = 0.0f;
var startingPos = transform.localPosition;
while (elapsedTime < time)
{
transform.localPosition = Vector2.Lerp(startingPos, target, (elapsedTime / time));
elapsedTime += Time.deltaTime;
yield return null;
}
transform.localPosition = target;
}
This is what happens when the resolution is anything but 1334x750
This is close to what I want but it is not exact and I feel like it should be
Is there a scaling thing I am not accounting for? Thanks in advance
Your answer
Follow this Question
Related Questions
Canvas, instantiate and adjust size of image to fit parent 0 Answers
Accidentally did 'something' and now positioning is all out of whack (canvas, camera, scaling?) 0 Answers
Display UI text On Controller 1 Answer
Why is the canvas size different for different people? 2 Answers
Swapping UI image element positions 1 Answer