0
\$\begingroup\$

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[];
    minerals.push(copper);
    minerals.push(gold);

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

    function Update() {
     if(rockHealth <= 0) {
         DestroyRock();
     }
    }

    function DestroyRock() {
     Destroy(rock);
     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);
    }
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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)].

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .