Choose random object from array not the same as the randomly chosen object before
Logically, I want to pick a random value from an array repeatedly but i do not want to pick the same one as before. In my actual game i am creating a hole for the ball to roll through but i do not want the hole to have the same position as then the ball will just fall strait through my game, without having to move to get to the hole, activating the spawning of another value through onCollisionExit.
Below is my code if you find it necessary -
using UnityEngine;
using System.Collections;
public class LevelSpawner : MonoBehaviour {
public float height;
public GameObject floor1;
public GameObject floor2;
public GameObject floor3;
public GameObject floor4;
public GameObject floor5;
public GameObject floor6;
public GameObject floor7;
public GameObject floor8;
public GameObject floor9;
public GameObject edge;
public GameObject edge2;
int index;
GameObject[] floors;
// Use this for initialization
void Start () {
floors = new GameObject [9] { floor1, floor2, floor3, floor4, floor5, floor6, floor7, floor8, floor9 };
Spawn();
}
public void Spawn ()
{
index = Random.Range(0,9);
height = height - 24;
GameObject floor;
floor = Instantiate(floors[index] , new Vector3(0, height), floors[index].transform.rotation) as GameObject;
Instantiate(edge, new Vector3(0, height + 36), Quaternion.identity);
edge2.transform.position = new Vector3(edge.transform.position.x, height + 96, edge2.transform.position.z);
}
}
The important bit is the first 4 lines of Spawn(), which is called from an another script.
I know there is the long way to do this by creating several other arrays for when the index is a certain value but not the one you just picked but that seems clunky and inefficient. I am aware of lists having watched the tutorial on them once but that is all and i am not comfortable with them.
Thanks,
Answer by phil_me_up · Jan 03, 2016 at 02:03 PM
Sounds like you want a shufflebag implementation: http://gamedevelopment.tutsplus.com/tutorials/shuffle-bags-making-random-feel-more-random--gamedev-1249
Admittedly i have not used the code exactly but the theory is relevant and i have used it.
Your answer
Follow this Question
Related Questions
How to change a game objects tag after it has been randomly selected? 0 Answers
IndexOutOfRangeException: Array index is out of range / EnemiesSpawner.cs:18) 3 Answers
How do i get array index that contains spesific string 1 Answer
is it possible toggle bool at editor by script? 1 Answer
C# Array Of Class Read Variables 2 Answers