- Home /
How do i give Coordinates (x, y) to an Array
Hello,
how can i set random coordinates to each number in array? AND how do i spawn it? Can someone help? I want to spawn 20 dots (I have array for that. Don't worry about this) with given random coordinates (on camera view) for each dot.
Thank you for answers.
This is my code:
void Start () {
for (int i = 0; i < dots.Length; i++) {
x = Random.Range (Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).x, Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0)).x);
y = Random.Range (Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).y, Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height)).y);
SpawnDots();
}
}
public void SpawnDots() {
Vector2 spawnPosition = new Vector2(x, y);
Instantiate(Dot, spawnPosition, Quaternion.identity);
}
Answer by Stratosome · Jul 16, 2018 at 10:21 PM
The problem is (I'm guessing without seeing the full code) that you get these random numbers, but never actually put them into the array. And then inside of your SpawnDots, you are only spawning a single one. I believe you probably want your SpawnDots function to spawn all of them. Something like this might be what you want:
private Vector2[] coordArray = new Vector2[20];
void Start () {
// Initialize array with random Vector2 values
for (int i = 0; i < coordArray.Length; i++) {
coordArray[i] = new Vector2(0, 0); // Make it a random vec instead
}
// After array has been initialized, spawn the dots
SpawnDots();
}
private void SpawnDots() {
// For each Vector2 in the array...
for (int i = 0; i < coordArray.Length; i++) {
Vector2 dot = coordArray[i];
// Spawn single dot
// ...
}
}
Thank you at first but how do i make Vector2 random, if I want the random values of Vector2 only in the camera's view.
This is my code, but Range takes only 1 argument: coordinationArray[i] = Random.Range (Camera.main.ScreenToWorldPoint(new Vector2(0, 0)));
so why do i get error: error CS1501: No overload for method Range' takes
1' arguments