so, i have 25 different-coloured cubes, all of the cubes have this c# script attached to them
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RandomPosition : MonoBehaviour {
public Vector3[] positions;
void Start () {
int randomNumber=Random.Range(0,positions.Length);
transform.position = positions[randomNumber];
}
}
this script, every time i start the game, change the position of my cubes in one of the 25 positions that i made, the problem is that a lot of cubes go to the same position, and i don’t want them to be in the same place. How do i do?
please help me, and sorry for my bad english. :')
Don’t use 25 scripts. Use 1 script to manage all your objects, then just put them in a collection (array or list) to reference them.
Try this:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RandomPosition : MonoBehaviour {
//Both must be same length
public GameObject[] cubes;
public List<Vector3> positions = new List<Vector3>();
void Start() {
foreach (GameObject cube in cubes) {
int randomIndex = Random.Range(0, positions.Count);
cube.transform.position = positions[randomIndex];
positions.RemoveAt(randomIndex);
}
}
}
Instead of an array, use a list, so that every time you pick a position, you can remove it from the list (or make a copy first, if you want to maintain your array). This way you ensure, that a position can only be used once and the random range will always pick a number from within the items that are left.