Bonnie49er1
Bonnie49er1

Reputation: 31

How do I instaniate a gameobject using a transform array randomly?

What I want to do is make a random key spawn point generator using transform arrays to get the key to spawn at a specific spot. Here is the code

public GameObject theKeyItself;
public Transform[] spawnPoints;
void Start()
{
    //GameObject selectedObject = spawnPoints.GetRandom(); (error)
    ChooseSpawnPoint();
    //chosenSP = spawnPoints(Random.Range(0, spawnPoints.Length).position); (error)
}
void ChooseSpawnPoint()
{
    //SpawnObjectsHere
}

Upvotes: 0

Views: 254

Answers (2)

sujoybyte
sujoybyte

Reputation: 636

If your theKeyItself is a prefab you have to use Instantiate and

public GameObject theKeyItself;
public Transform[] spawnPoints;


void Start()
{
    Transform theKeyItselfCopy = Instantiate(theKeyItself).transform;

    Transform randomSpawnPoint = spawnPoints[Random.Range(0, spawnPoints.Length)];
    ChooseSpawnPoint(theKeyItselfCopy, randomSpawnPoint);

}
void ChooseSpawnPoint(Transform key, Transform spawnPoint)
{
    key.position = spawnPoint.position;
}

Upvotes: 0

CorrieJanse
CorrieJanse

Reputation: 2598

Break your question down into sub questions

  • How do I instantiate a game object using a transform?

Transform t = Instantiate(transformPref, position, rotation, parent);

  • How do I select from an array randomly?

arr[Random.Range(0, arr.Count)];

Now put them together

Transform transformPref  = transformArray[Random.Range(0, transformArray.Count)];
Transform t = Instantiate(transformPref, position, rotation, parent);

Upvotes: 1

Related Questions