- Home /
[Help] How Do I Randomly Spawn Game Objects On Specific Coordinates?
Hello all, I'm making a game which requires the player to find a door which has spawned randomly in the map with a simple portal animation, which when entered, will project a screen with the text "YOU WIN". I did figure out those screens, movement, and everything, except spawning the door on random 4-5 places, I am a literal beginner who started unity almost a week ago, any code which I could understand (C#) would be appreciated, Thanks :)
Answer by Simonotos · Oct 11, 2020 at 03:54 PM
Random r = new Random()
int door_count = r.Range(1,5)
switch(door_count){
case(1) :
door.transform.position = first_point;
break;
case(2) :
door.transform.position = second_point;
break;
case(3) :
door.transform.position = third_point;
break;
case(4) :
door.transform.position = fourth_point;
break;
}
The points refers to public Vector2/3 where u put the position u desire to spawn door if u can't manage to use Random class u can try with System.Random Hope it helps u!
Answer by tekinomer241 · Oct 19, 2020 at 01:30 PM
You may choose some specified(by you) points to be spawn points and then pick one of them randomly. You can define it by:
[SerializeField] private Transform[] spawnPoints;
And of course to instantiate the door you need to have it:
[SerializeField] private GameObject door;
To spawn the door you can use a code like this one:
Instantiate(door, _spawnPoints[Random.Range(0, _spawnPoints.Length)]);
Don't forget to put the right objects to the script component in the inspector.
Answer by BRX99_GS · Oct 19, 2020 at 01:14 PM
I don't understand you very well but maybe this will help.
// Create and position the object.
GameObject door = GameObject.CreatePrimitive(PrimitiveType.door);
door.transform.position = new Vector3(0.0f, -1.0f, 0.0f);
door
is not part of the PrimitiveType enumYou are setting an absolute position, not a random position as asked by the original poster