- Home /
Objects spawning in relation to resolution
Hello everyone, I'm trying to have objects spawn above the screen and then fall down. This is how I did it:
public Canvas canvas;
public GameObject prefab1;
public GameObject prefab2;
int minSpawnDistance = 50;
int maxSpawnDistance = 550;
private void Start()
{
StartCoroutine(SpawnPrefab());
}
IEnumerator SpawnPrefab()
{
while (true)
{
int chosenPrefab = Random.Range(0, 2);
int chosenX = Random.Range(minSpawnDistance, maxSpawnDistance + 1);
//this is just for randomizing the rotation
Vector3 euler = transform.eulerAngles;
euler.z = Random.Range(0f, 360f);
transform.eulerAngles = euler;
if (chosenPrefab == 0)
{
GameObject prefab = Instantiate(prefab1, new Vector2(chosenX, 1400), Quaternion.Euler(euler), canvas.transform);
}
else
{
GameObject prefab = Instantiate(prefab2, new Vector2(chosenX, 1400), Quaternion.Euler(euler), canvas.transform);
}
yield return new WaitForSeconds(1f);
}
}
So basically, I choose a random X value (one that is between 50 and 550) and spawn it with a Y value of 1400 (so X = 50-500 and Y = 1400).
The issue arises when I change the Game View to fullscreen or just change the resolution of the game view. Then, the prefabs start spawning in the middle of the screen, because the canvas gets bigger. How do I make them always spawn above the canvas, regardless of how big it is? Any input will be greatly appreciated.
Answer by Ishkur · Dec 21, 2019 at 10:06 PM
The prefab you're instantiating is being parented to canvas.transform. I think canvas.transform changes as your change resolution.
Can you try scaling chosenX as a percentage of Screen.width?
For example, try
int chosenX = Screen.width / 2;
See if that puts the object right in the middle of the screen regardless of resolution. If it works I think you can take it from there.
Thank you!!! I tried camera.pixelWidth, canvas.rect.width, regular transform.position and Screen.Width was the one that worked! $$anonymous$$aybe copy and paste your @Ishkur comment as an answer so I can accept it? Thank you!!
He's how it ended up:
public Canvas canvas;
public Camera mainCamera;
public GameObject prefab1;
public GameObject prefab2;
public GameObject main$$anonymous$$enu;
private void Start()
{
StartCoroutine(SpawnPrefab());
}
IEnumerator SpawnPrefab()
{
while (true)
{
int chosenPrefab = Random.Range(0, 2);
int chosenX = Random.Range(0, Screen.width);
int chosenY = Screen.height + Screen.height / 30;
Vector2 spawnPos = new Vector2(chosenX, chosenY);
Vector3 euler = transform.eulerAngles;
euler.z = Random.Range(0f, 360f);
transform.eulerAngles = euler;
if (chosenPrefab == 0)
{
GameObject prefab = Instantiate(prefab1, spawnPos, Quaternion.Euler(euler), main$$anonymous$$enu.transform);
print(snowflake.transform.position);
}
else
{
GameObject prefab = Instantiate(prefab2, spawnPos, Quaternion.Euler(euler), main$$anonymous$$enu.transform);
}
yield return new WaitForSeconds(8f);
}
}