Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Afavar · Sep 07, 2014 at 11:05 PM · randomspawnrepeat

Random Positions without Repeating

Hi everyone, i want my objects to spawn at random positions without repeating the same position. For example there are 7 locations and and i basically want them to shuffle.

I tweaked the Spawner script that is used in the 2D Platformer demo to have random spawns. It is below. Any idea how can to avoid repeating?

 using UnityEngine;
 using System.Collections;
 
 
 public class SpawnerMY : MonoBehaviour
 {
     public float spawnTime = 5f;        // The amount of time between each spawn.
     public float spawnDelay = 3f;        // The amount of time before spawning starts.
     public GameObject[] enemies;        // Array of enemy prefabs.
     public Transform[] teleport;
 
     void Start ()
     {
         // Start calling the Spawn function repeatedly after a delay .
         InvokeRepeating("Spawn", spawnDelay, spawnTime);
 
     }
 
 
 
     void Spawn ()
     {
 
     
         // Instantiate a random enemy.
         int enemyIndex = Random.Range(0, enemies.Length);
         int tele_num = Random.Range(0,7);
         Instantiate(enemies[enemyIndex], teleport[tele_num].position, teleport[tele_num].rotation);
 
         // Play the spawning effect from all of the particle systems.
         foreach(ParticleSystem p in GetComponentsInChildren<ParticleSystem>())
         {
             p.Play();
         }
     }
 }
 
 
Comment
Add comment · Show 5
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Afavar · Oct 14, 2014 at 06:06 PM 0
Share

Nobody has an idea?

avatar image KpjComp · Oct 14, 2014 at 06:17 PM 0
Share

Create a list of int's, then select a random item from the list then remove it. If you need a script example let us known.

avatar image Afavar · Oct 14, 2014 at 07:56 PM 0
Share

Well i tried to achieve something like that and came up with the code down below. But it still repeats so i have kinda no idea what to do.

 // Public so you can fill the array in the inspector
         public Transform[] scenarios; 
         public float spawnTime = 5f;        // The amount of time between each spawn.
         public float spawnDelay = 3f;        // The amount of time before spawning starts
         public GameObject[] enemies;        // Array of enemy prefabs.
     
         void Start ()
         {
             // Start calling the Spawn function repeatedly after a delay .
             InvokeRepeating("Spawn", spawnDelay, spawnTime);
             
         }
         
     
         void Spawn ()
         {
             Shuffle (scenarios);
             
             // Instantiate a random enemy.
             int enemyIndex = Random.Range(0, enemies.Length);
             int tele_num = Random.Range(0, scenarios.Length);
             
             Instantiate(enemies[enemyIndex], scenarios[tele_num].position, scenarios[tele_num].rotation);
             
             // Play the spawning effect from all of the particle systems.
             foreach(ParticleSystem p in GetComponentsInChildren<ParticleSystem>())
             {
                 p.Play();
             }
         }
         
         
         void Shuffle(Transform[] a)
         {
             // Loops through array
             for (int i = a.Length-1; i > 0; i--)
             {
                 // Randomize a number between 0 and i (so that the range decreases each time)
                 int rnd = Random.Range(0,i);
                 
                 // Save the value of the current i, otherwise it'll overright when we swap the values
                 Transform temp = a[i];
                 
                 // Swap the new and old values
                 a[i] = a[rnd];
                 a[rnd] = temp;
             }
             
             // Print
             for (int i = 0; i < a.Length; i++)
             {
                 Debug.Log (a[i]);
             }
         }
 

avatar image KpjComp · Oct 14, 2014 at 08:29 PM 0
Share

Well your shuffling each time, and then selecting a random item from a random list, so it will stay random. :)

You need to Shuffle first in your Start, store a private int that starts at 0, then increase this after each spawn, when this gets to your lists count, reset back to 0, and optionally reshuffle.

avatar image Afavar · Oct 15, 2014 at 03:23 PM 0
Share

Can you help me with that? I am new with the c#.

3 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by fafase · Oct 15, 2014 at 03:53 PM

 [SerializeField] private int range = 20;  // Hom many items you want, will show in Inspector
 List<int>list = new List<int>(); 
 void Start()
 {
    FillList();
 }
 
 void FillList()
 {
    for(int i = 0; i < range; i++)
    {
       list.Add(i);
    }
 }
 
 int GetNonRepeatRandom()
 {
     if(list.Count == 0){
         return -1; // Maybe you want to refill
     }
     int rand = Random.Range(0, list.Count);
     int value = list[rand];
     list.RemoveAt(rand);
     return value;
 }


Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Afavar · Oct 15, 2014 at 09:12 PM 0
Share

How can i connect the value int to the void Spawn(). I tried the code below but didnt work as i expected. How can i fix it?

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 public class ShuffleList : $$anonymous$$onoBehaviour {
 
     // Public so you can fill the array in the inspector
     public Transform[] scenarios; 
     public float spawnTime = 5f;        // The amount of time between each spawn.
     public float spawnDelay = 3f;        // The amount of time before spawning starts
     public GameObject[] enemies;        // Array of enemy prefabs.
 
 
     [SerializeField] private int range = 20;  // Hom many items you want, will show in Inspector
     List <int> list = new List<int> (); 
 
 
 
 
     void Start()
     {
         InvokeRepeating("Spawn", spawnDelay, spawnTime);
         FillList();
     }
     
     void FillList()
     {
         for(int i = 0; i < range; i++)
         {
             list.Add(i);
         }
     }
     
     int GetNonRepeatRandom()
     {
 
 
         if(list.Count == 0){
             return -1; // $$anonymous$$aybe you want to refill
         }
         int rand = Random.Range(0, list.Count);
         int value = list[rand];
         list.RemoveAt(rand);
         return value;
     }
 
     void Spawn () 
     {
 
 
         // Instantiate a random enemy.
         int enemyIndex = Random.Range(0, enemies.Length);
         //int tele_num = Random.Range(0, scenarios.Length);
         
         Instantiate(enemies[enemyIndex], scenarios[value].position, scenarios[value].rotation);
         
 
     }
 
 
 }
 
avatar image KpjComp · Oct 15, 2014 at 10:07 PM 1
Share

int enemyIndex = GetNonRepeatRandom();

But remember what do you want to happen when all random positions have be used, if you want to randomize again, just put fillList() in the line that says return -1;

avatar image Afavar · Oct 16, 2014 at 04:09 PM 0
Share

It worked great, thank you.

avatar image
0

Answer by Eno-Khaon · Oct 14, 2014 at 06:19 PM

One possible solution would be to use a List for the positions to place them. http://answers.unity3d.com/questions/284054/lists-c.html

You can populate the list when ready to use it, then remove the specific entries from it as you use them. That way, you could randomly choose a position from the List and never have to worry about repeating.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Maynk · Dec 14, 2020 at 12:25 PM

Don't Take An Effort, Do Easier in Unity C#

 //Random.Range Position But Not Repeat
 
 {
 public GameObject spawnEnmy;
 
     public List<Transform> spnPosns = new List<Transform>();
 
     //Queue<Transform> spnPnts = new Queue<Transform>();
 
     float spnIn, spwnOut;
 
     private void Awake() => spnIn = spnPosns.Count;
 
     private void Start()
     {
         while (spwnOut <= (int)spnIn)
         {
             if (spnPosns.Count >= 0)
             {
                 var rdmNxt = spnPosns[Random.Range(0, spnPosns.Count)];
                 spwnIng(spawnEnmy, rdmNxt);
                 spnPosns.Remove(rdmNxt);
             }
 
             spwnOut++;
             Debug.Log(spnPosns.Count);
         }
     }
 
     public static void spwnIng(GameObject spwnObj, Transform spwnPos) => Instantiate(spwnObj, spwnPos.position, Quaternion.identity);
 }

When You Run on Unity Do Work fine But in the Last "ArgumentOutOfRangeException" Don't penic Because Index List<> Size will Zero, This Not A Coding this are Debug Mistake Because Debug Skip if() condion in this, Anyway Because code in Start() So Not Wrong with Them

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Endless/infinite runner random enemy spawning multi lane 1 Answer

How to randomly replace the main platform with additional ones? 0 Answers

Drop item from airplane 1 Answer

Spawning targets on 2 of 4 pre-defined locations using an array and empty game objects? 1 Answer

avoid overlap problem when randomly instantiating 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges