Hi,
Newby on Unity here sorry if this is an already answered question
I’m instantiating GameObject from prefab and positioning it on my scene with Instantiate()
Now I want my game to support as many screen size as possible, so how can I set the correct position and / or scale of my GameObject according to screen size?
How do you do that on your games?
I made a script for detecting a game objects pixel scale according to screen size. Just add this to your game objects to find the pixel width and length based on the device.
void Start ()
{
float depth = gameObject.transform.lossyScale.z;
float width = gameObject.transform.lossyScale.x;
float height = gameObject.transform.lossyScale.y;
Vector3 lowerLeftPoint = Camera.main.WorldToScreenPoint( new Vector3( gameObject.transform.position.x - width/2, gameObject.transform.position.y - height/2, gameObject.transform.position.z - depth/2 ) );
Vector3 upperRightPoint = Camera.main.WorldToScreenPoint( new Vector3( gameObject.transform.position.x + width/2, gameObject.transform.position.y + height/2, gameObject.transform.position.z - depth/2 ) );
Vector3 upperLeftPoint = Camera.main.WorldToScreenPoint( new Vector3( gameObject.transform.position.x - width/2, gameObject.transform.position.y + height/2, gameObject.transform.position.z - depth/2 ) );
Vector3 lowerRightPoint = Camera.main.WorldToScreenPoint( new Vector3( gameObject.transform.position.x + width/2, gameObject.transform.position.y - height/2, gameObject.transform.position.z - depth/2 ) );
float xPixelDistance = Mathf.Abs( lowerLeftPoint.x - upperRightPoint.x );
float yPixelDistance = Mathf.Abs ( lowerLeftPoint.y - upperRightPoint.y );
print( "This is the X pixel distance: " + xPixelDistance + " This is the Y pixel distance: " + yPixelDistance );
print ("This is the lower left pixel point: " + lowerLeftPoint);
print(" This is the upper left point: " + upperLeftPoint );
print ("This is the lower right pixel point: " + lowerRightPoint);
print(" This is the upper right pixel point: " + upperRightPoint);
}
I used this and then adjusted my game objects manually accordingly because although it proves as a good guide to know how much you need to adjust everything, I think it is best to manually adjust the scale/position because to do this by code will take unnecessary overhead, but if you just take a bit of time and do it manually, you will end up with exactly what you want at no cost, but your time. On the other hand, if you want to do it manually maybe this will give you a head start.
Unfortunately it doesn’t allow me to post nice looking code as a comment and I didn’t want to answer as I’m not sure if this completely answers your question…
@highpockets How can i set scale for object base on screen size? suppose i want to add 10 box prefab programatically in raw so how i can set scale to fit different screens.