Copying gameObject doesn't work as intended
Hello!
I'm new to Unity and I have an interesting problem.
I wanted to create 10 circles that appear at random places on the screen and move in random directions. I made one circle and copied it 9 times, thinking it would be okay. But when I run my game, all 10 circles appear on the same place and move to the same direction. They are basically the same. The interesting part is, when I add some print() lines to the script they become unique, so I get the 10 circles at random places going in random directions...
What am I doing wrong? Should I copy gameObjects differently?
The script is like this: (only the random position part, because running this only produces the error as well).
public class $$anonymous$$enuBackgroudCircleScript : $$anonymous$$onoBehaviour {
private Random random;
private float xCoordinate;
private float yCoordinate;
void Start ()
{
random = new Random();
var circleSize = Screen.height > Screen.width ? random.Next(Screen.width / 2) : random.Next(Screen.height / 2);
gameObject.transform.transform.localScale = new Vector3(circleSize, circleSize);
gameObject.transform.position = new Vector3(
random.Next((int)Camera.main.ScreenToWorldPoint(new Vector3(0, 0)).x,(int)Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height)).x),
random.Next((int)Camera.main.ScreenToWorldPoint(new Vector3(0, 0)).y,(int)Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height)).y));
}
}
If I add a random print() (for example print("123"); ) to the code then all circles appear in random places, like they should be.
Answer by S0m30n39 · Dec 17, 2016 at 04:01 PM
Alright, I think I found a "solution". I switched System.Random to UnityEngine.Random and it seems to be working. I couldn't debug what the problem was, because during debug, even System.Random worked.
Your answer
![](https://koobas.hobune.stream/wayback/20220612102521im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
,Instantiate at touch position 0 Answers
How to destroy on exiting PlayMode/EditMode? 1 Answer
I need help about Basic Basketball Game 0 Answers
Create gameobject in other scene... 0 Answers
Why is my object not instantiating multiple times? 0 Answers