0

im creating a game where the player needs to find and pick up a certain number of keys. Currently ive got a spawn container that generates 5 keys in given locations. I want to be able to generate the 5 keys in 5 random locations. So lets say i have 10 spawn points, i want it to randomly pick any of the 5 points and place a key there.

I have the following code so far

  using UnityEngine;
using System.Collections;

public class KeySpawnManager : MonoBehaviour 
{
    // array to store spawnpoints
    private Transform[] spawnTransformList;

    // integer to store number of spawnpoints
    private int numberOfSpawnpoints;

    // the prefab we're going to spawn
    public GameObject prefab;

    private int collectedCount = 0;

    private int currentTime = 0;


    // Singleton Instance
    public static KeySpawnManager Instance { get; private set; } 

    // AWAKE Function - fired on initialization
    void Awake () 
    {
        if (Instance == null) Instance = this;
        else Destroy( gameObject ); 

        numberOfSpawnpoints = transform.childCount;

        spawnTransformList = new Transform[numberOfSpawnpoints];

        for (int i = 0; i < numberOfSpawnpoints; i++) 
        {
            // add the spawn to the array
            spawnTransformList[i] = transform.GetChild(i); // return transform Component of each child object
        }

        for (int j = 0; j < numberOfSpawnpoints; j++)
        {
            GameObject newPrefab = (GameObject) Instantiate(prefab, spawnTransformList[j].position, spawnTransformList[j].rotation);

            newPrefab.transform.parent = transform.position;
        }

    }


}

Any ideas on how to do this? thanks

Kingspud
  • 65
  • 6
  • what is it exactly that your code does and what is it that your code cant do? – Milad Qasemi Apr 29 '16 at 05:59
  • So ive created 5 empty game objects, and the code above spawns a key prefab in the position of each empty game object. Im trying to change it to 10 empty game objects but it only spawns 5 keys and choses a random one of the 10 empty objects – Kingspud Apr 29 '16 at 06:00

2 Answers2

2

create your ten empty gameobject in a list then shuffle the list using Fisher-Yates shuffle then use the first five elements of the list and spawn keys in them

Here is the implementation of a Fisher-Yates shuffle in c#

Community
  • 1
  • 1
Milad Qasemi
  • 3,011
  • 3
  • 13
  • 17
0

Create a random method using random class that you can pass in the total number of spawn points. Have it return then index for your spawn location.

Codyj110
  • 548
  • 1
  • 5
  • 13