- Home /
how to use GameObject only once from array with random
how to use GameObject only once from array with random
my try with JavaScript :
var cards : GameObject[]; // 16 cards
Instantiate(cards[Random.Range(0, cards.length)].gameObject, transform.position, transform.rotation);
Answer by Jessy · Feb 25, 2011 at 12:18 PM
Is it okay to take the Game Objects out of the collection? If so, just make a List of them and remove them from the List:
import System.Collections.Generic;
var cards : List.<GameObject>; // 16 cards ONLY to start with
function ChooseCard () { if (cards.Count == 0) return;
var index = Random.Range(0, cards.Count);
Instantiate(cards[index], transform.position, transform.rotation);
cards.RemoveAt(index);
}
Otherwise, you can make a List of the indices, instead:
import System.Collections.Generic;
var cardIndeces : List.<int>;
function Start () { cardIndeces = new List.<int>(new int[16]); for (var i = 0; i < 16; ++i) cardIndeces[i] = i; }
function ChooseCard () { if (cardIndeces.Count == 0) return;
var index = Random.Range(0, cardIndeces.Count);
Instantiate(cards[index], transform.position, transform.rotation);
cardIndeces.RemoveAt(index);
}
List of the indices is my solution, thank you very much ! :)
Your answer
