- Home /
Wrong positions of new objects. Problem with scaling
Hi guys, I need an advice: I create some objects from prefab dynamically and add it to GameObject, which already in UI Canvas. Canvas has parameter "Ui Scale Mode" which has been set as "Scale with screen size". The problem is that objects which I have added have coords which are not the same as Vector3 value which I pass to Translate method of these objects. For example if I add my Object to coords(54, -108, 0) it adds it to position(71.7608, -143.5216, 0). If I chenge screen dimentions, the values will be different. How can I manage it? Thanks. I add new objects with script:
public class GridGamePanel : MonoBehaviour {
public Transform linePrefab;
private static int LINE_WIDTH = 108;
public void drawGridFromScratch ()
{
for (var y=1; y<3; y++) {
for (var x=0; x<3; x++) {
Transform lineObject = (Transform) GameObject.Instantiate(linePrefab, new Vector3 (0, 0, 0), Quaternion.identity);
lineObject.SetParent(this.transform, false);
Vector3 newPosition = new Vector3 (x * LINE_WIDTH+LINE_WIDTH/2, y * -LINE_WIDTH, 0);
print("new position for horizontal - "+newPosition);
lineObject.Translate(newPosition);
}
}
for (var x=1; x<3; x++) {
for(var y=0; y<3; y++){
Transform line = (Transform)Instantiate (linePrefab, new Vector3 (0, 0, 0), Quaternion.identity);
line.SetParent (this.transform, false);
line.Translate(new Vector3 (x * LINE_WIDTH, y * -LINE_WIDTH - LINE_WIDTH/2, 0));
line.Rotate(0,0,90);
}
}
}
}
Answer by Joyrider · Feb 09, 2015 at 09:54 AM
A little background first. Basically, with the ScaleMode "Scale with screen size", what is happening is the positions given to your canvas are interpreted as being positions in the reference resolution and thus not in your current resolution. These are automatically scaled by the canvasScaler to scale with your screen; hence the difference in position between the position you set and the actual position your object is displayed at.
This is not a solution on its own, but an explanation of what is happening by choosing "Scale with screen size".
However, you can get the scaling of your canvas from the RectTransform of your canvas. So with your desired position and the scale applied to you canvas you can compute the position in your reference resolution.
In practice, from what I gather, you RectTransform scale is 1.3289 so you should set the position to (54/1.3289, -108/1.3289, 0) and your final display position should be about (54, -108, 0).
I didn't test this, but it should work imo.
Your answer
Follow this Question
Related Questions
Is there a way of correctly parenting to get scales and positions of gameObjects right? 2 Answers
Weird Positioning Problem? 1 Answer
Converting Pixels to Units and Position Prefab 1 Answer
Dynamic scaling when instantiated or different prefabs? 1 Answer
How to control position of GUITexture when its inside a prefab 0 Answers