Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How can I randomize a child position to spawn a game object?

Discussion in 'Scripting' started by ajcombest3, Mar 16, 2018.

  1. ajcombest3

    ajcombest3

    Joined:
    Mar 13, 2018
    Posts:
    27
        public GameObject astroidPrefab;
    // Use this for initialization
    void Start () {
    Transform freePosition = NextFreePosition();
    GameObject enemy = Instantiate(astroidPrefab, freePosition.position, Quaternion.identity) as GameObject;
    enemy.transform.parent = freePosition;
    }

    // Update is called once per frame
    void Update () {

    }
    Transform NextFreePosition() {
    foreach (Transform childPositionGameObject in transform) {
    if (childPositionGameObject.childCount == 0) {
    return childPositionGameObject;
    }
    }
    return null;
    }
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
  3. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
  4. coldpizzapunk

    coldpizzapunk

    Joined:
    Aug 20, 2014
    Posts:
    30
    Some things I learned with using Random.Range is to use it in conjunction with Random.InitState if you want to appear really random. I was having problems with Random.Range always doing the same order every time the game ran (Not truly random). So if you want it to be a different random pattern every play you should use Random.InitState too. Also, Random.Range when used with an INT does not include the Maximum number in your range, something I didn't think about at first.

    Example of what I have in Unity 2017.3

    I start with a transform array and int:

    Code (CSharp):
    1. //Array of spawn points for characters
    2. public Transform[] spawnPoints;
    3. private int spawnPointIndex;
    In my section to find a random int every time its run:

    Code (CSharp):
    1. //Randomize the Seed to give more random illusion by changing the seed based on current date and time
    2. Random.InitState(System.DateTime.Now.Millisecond);
    3.  
    4. //Find a random spawn point between 0 and Spawn Points total array
    5. spawnPointIndex = Random.Range(0, spawnPoints.Length);
    Then I do a instantiate to create a prefab instance.