I'm trying to make a rock that after you break it, it will spawn a random item from the minerals array. How can I pick a random item from the minerals array and then instantiate it?

    var rockHealth : int = 50;
    var rock : GameObject;
    var speed : int = 8;
    var rb : Rigidbody;

    var copper : Transform;
    var gold : Transform;

    var minerals : Transform[];

    function DeductPoints(hitpoints : int) {
     rockHealth -= hitpoints;

    function Update() {
     if(rockHealth <= 0) {

    function DestroyRock() {
     var position : Vector3 = Vector3(Random.Range(-1.0, 1.0), 0, Random.Range(-1.0,1.0));
     Instantiate("random mineral would go here", rock.transform.position + Vector3(0,0,0) + position, Quaternion.identity);

Minerals/items are gameObject, not Transform. Your instantiation code at DestroyRock() should be like:

Instantiate(minerals[Random.Range(0,1)], position, Quaternion.identity);

In minerals[Random.Range(0,1)] 0 and 1 are index of the minerals array. If there were 5 items it would be minerals[Random.Range(0,5)].


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.