Random Spawn locations

Hey guys,I am getting more into javascript.

I am making a game but I need a random spawn location.

I want the player to spawn in one of the nine locations(blue flooring).

hope you can help

Very useful for you

using UnityEngine;

using System.Collections;

public class SpawnRandom : MonoBehaviour {
 //gameobject for spawning 
 public GameObject spawnObj;
 //set custom range for random position
 public float MinX = 0;
 public float MaxX = 10;
 public float MinY = 0;
 public float MaxY = 10;

 //for 3d you have z position
 public float MinZ = 0;
 public float MaxZ = 10;

 //turn off or on 3D placement
 public bool is3D = false;

 void SpawnObject() {
    float x = Random.Range(MinX,MaxX);
    float y = Random.Range(MinY,MaxY);
    float z = Random.Range(MinZ,MaxZ);

    if(is3D) {
       Instantiate(spawnObj, new Vector3(x,y,z), Quaternion.identity) as GameObject;
    }
    else {
       Instantiate(spawnObj, new Vector3(x,y,0), Quaternion.identity) as GameObject;
    }
 }
}

You can set a few positioning array to make the spawn points randomly like(C#):

public Vector3 spawnPos[] = new Vector3[9];

void Start(){
  spawnPos[0] = Vector3(10,10,10)
  spawnPos[1] = Vector3(20,20,20)
  spawnPos[2] = Vector3(30,30,30)
  //Keep going giving the positions
}

void Update(){
  spawnPoint = 0;
  spawnPoint = Random.Range(0, 8);
  Instantiate(playerObj, spawnPos[spawnPoint], Quaternion.identity);
}

Hope this can help you!
Good Luck!

If you want to place those objects to the scene in Editor and then spawn the player on one of them make a script with public array of spawn points and then instantiate the player on randomly chosen position. This way you do not need to enter the positions manualy and see in the editor where the spawn points are exactly (while you do not see them in-game if they have no mesh).

Here is a simple example in C#

public GameObject[] spawnPoints;
public GameObject playerObject;

void Start() {
    SpawnPlayer();
}

void SpawnPlayer() {
    int spawn = Random.Range(0, spawnPoints.Length);

    GameObject.Instantiate(playerObject, spawnPoints[spawn].transform.position, Quaternion.identity);
}

You can attach this to an empty game object.

@TheHoongs, May I offer a completely different approach than what appears to be common, at least from your question’s current answers.

Place all of your Spawners beneath the same parent on the hierarchy and then pick a random number from range 0 to 8. Then instantiate your player at the location of the parents (0-8) child.

I don’t know if your object management in the hierarchy will support this way of doing it, but to me it would be the easiest. You may have to adjust the Z coordinate so that it spawns at the proper height versus the middle of the player being at the floor.

Hope this helps, please let me know. There are many ways to do this, this one just the easiest to type up, lol.