Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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 primus88 · Jun 03, 2013 at 10:23 AM · spawnrandomize

Spawning random object at predefined locations

Hello,

I searched around and found different pieces of code that even though separately cover all parts of my problem, when put together are not working..

Here is what I need to do :

  1. I have 14 spawn points located on my terrain.

  2. I have 14 game objects to spawn.

  3. What I need is to spawn one object (chosen at random, let's say Number3 from gameobject list) at spawn point Nr1 (spawn points can be iterated based on their number)

  4. Next iteration is to choose again a new object from the updated gameobject list(the gameobject list, minus Number3 which was previously spawned) and spawn it at spawn point Nr2

  5. Iterations continue until all objects are uniquely spawned on all the spawn points.

I need this for my game world map, where the objects will represent loading triggers for the respective scenes.

Help is very much appreciated as I am still a newbie in scripting. Thank you.

Comment
Add comment
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

2 Replies

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

Answer by Chronos-L · Jun 03, 2013 at 11:12 AM

One way to do it is to shuffle the spawn point array, then you can do something like this:

 for( int i = 0; i < spawnPoints.length; ++i ) {
    /*Spawn gameObjectArray[i] at spawnPoints[i];*/
 }

To do a shuffle, you can go for a Fisher–Yates shuffle:

 Transform [] myArray = ...;
 
 int i = myArray.length;
 
 while( --i >= 0 ) {
    int randIndex = Random.Range( 0, myArray.length );
 
    //Swap i with a random index
    Transform temp = myArray[i];   
    myArray[i] = myArray[randIndex];
    myArray[randIndex] = temp;
 }



If you are using a collection to store the spawn points, then you can go for this:

 List<Transform> spawnPoints = ...;
 
 //You can use either collections or array to store the spawned object, it doesn't matter
 GameObject[] spawnThis = ...;
 
 ...
 
 for( int i = 0; i < spawnThis.Length; ++i  ) {
    int randIndex = Random.Range( 0, spawnPoints.Count );
    Transform sp = spawnPoints[randIndex];
    spawnPoints.RemoveAt( randIndex );
 
    /*Spawn spawnThis[i] at sp*/
 }
 

Comment
Add comment · Show 11 · 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 primus88 · Jun 03, 2013 at 12:38 PM 0
Share

Ok, I'm using the second piece of code. I'm creating the list and even though it says there are 14 objects in it, this part is giving me different, numbers of objects.

  int randIndex = Random.Range( 0, spawnPoints.Count );
 Transform sp = spawnPoints[randIndex];
 spawnPoints.RemoveAt( randIndex );

Each time I restart the game it shows : 3,1,5 etc (a random number of spawnpoints)

How to modify it so that I have the maximum 14 objects ?

avatar image Chronos-L · Jun 03, 2013 at 01:50 PM 0
Share

3,1,5 were the values of which variable? spawnPoints.Count or randIndex?

avatar image primus88 · Jun 03, 2013 at 01:57 PM 0
Share

I mean the number of spawn points (3 spawn points, 1 spawn point, 5 spawn points etc)

Let's take the case when 5 spawnpoints were shown, indeed they were set randomly in the list, but they were only 5 ins$$anonymous$$d of 14.

This is my code :

 public class World$$anonymous$$apRandomizer : $$anonymous$$onoBehaviour {
     
     public List<Transform> spawnPoints ;
     public int sizeOfList;
     public GameObject[] spawnThis;
     
     // Use this for initialization
     void Start () {
         Invoke("Generate", 0);
     }
     
     // Update is called once per frame
     void Update () {
     
     }
     
     void Generate()
         {
         
         GameObject[] go = GameObject.FindGameObjectsWithTag("BattlePointSpawner");
         foreach(GameObject BP in go)
             Addtarget(BP.transform);
         }
     
     public void Addtarget(Transform BP)
         {
     spawnPoints.Add(BP);
     sizeOfList = spawnPoints.Count;
         Invoke("Spawn", 0);
         }    
     
     void Spawn()
     {
         for( int i = 0; i < spawnThis.Length; ++i ) 
             {
             Debug.Log (sizeOfList);
                 int randIndex = Random.Range( 0, sizeOfList );
                 Transform sp = spawnPoints[randIndex];
                 spawnPoints.RemoveAt( randIndex );
             
             }
     }
         
     
 }


Error that give me after I run the game : ArgumentOutOfRangeException: Argument is out of range. Parameter name: index System.Collections.Generic.List`1[UnityEngine.Transform].get_Item (Int32 index) (at /Applications/buildAgent/work/b59ae78cff80e584/mcs/class/corlib/System.Collections.Generic/List.cs:633) World$$anonymous$$apRandomizer.Spawn () (at Assets/$$anonymous$$yScripts/World$$anonymous$$apRandomizer.cs:42)

avatar image Chronos-L · Jun 03, 2013 at 02:16 PM 0
Share

Let me show you how I will do it, and you can compare it to your code and see what's the difference between $$anonymous$$e and yours.

Code not tested

 public Transform[] spawnPoints;
 public GameObject[] spawnThese;
 
 void Start() {
     //I get these from Google, they should work
     //If not, just google for "C# convert array to list" or ".NET convert array to list"
     List<Transform> sp = spawnPoints.ToList(); 
     List<Transform> sp = new List<Transform>( spawnPoints );
 
     if( spawnThese.length <= spawnPoints.length ) { //Only spawn when there are enough spawnPoints
         for( int i = 0; i < spawnThese.length; ++i  ) {            
             int randIndex = Random.Range( 0, sp.Count );
             Transform selectedPoint = sp[randIndex];
             sp.RemoveAt( randIndex );
 
             /*Spawn spawnThese[i] at selectedPoint*/
         }
     }
 }
avatar image Chronos-L · Jun 03, 2013 at 02:18 PM 0
Share

If you don't $$anonymous$$d, have you give the first approach a shot?

Show more comments
avatar image
0

Answer by Mahtrok · Jun 03, 2013 at 06:55 PM

        for( int i = 0; i < spawnThis.Length; ++i ) 
          {
          Debug.Log (sizeOfList);
           int randIndex = Random.Range( 0, sizeOfList );
           Transform sp = spawnPoints[randIndex];
           spawnPoints.RemoveAt( randIndex );
          }


You are changing the values inside your list during the loop, so that your sizeOfList != spawnPoints.Count. If your Random,Range then tries to get the spawnPoint from 0 to sizeOfList it may get an index of your list no longer existing ( sizeOfList == 14, spawnPoints.Count == 13 ) which ends up in a null reference exception. You should not Remove the spawnPoint inside the loop OR you should simply reduce your sizeOfList after RemoveAt by 1 as well.

Greetz

Comment
Add comment · Show 10 · 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 primus88 · Jun 03, 2013 at 07:55 PM 0
Share

Hey $$anonymous$$ah,, Thanks for the input. Indeed I realized I was doing it wrong.

Here is my code now which iterates correctly :

 public class World$$anonymous$$apRandomizer : $$anonymous$$onoBehaviour {
     
     public List<Transform> spawnPoints ;
     public int sizeOfList;
     public GameObject[] spawnThis;
     public List<Transform> prefabTransforms; 
     // Use this for initialization
     void Start () {
         Invoke("Generate", 0);
     }
     
     // Update is called once per frame
     void Update () {
     
     }
     
     void Generate()
         {
         
         GameObject[] go = GameObject.FindGameObjectsWithTag("BattlePointSpawner");
         foreach(GameObject BP in go)
             Addtarget(BP.transform);
         }
     
     public void Addtarget(Transform BP)
         {
     spawnPoints.Add(BP);
     sizeOfList = spawnPoints.Count;
         Invoke("RandomizeBuiltinArray", 0);
         }    
     
         void RandomizeBuiltinArray()
     {
         prefabTransforms = new List<Transform>();
     for (var i = spawnPoints.Count - 1; i >= 0; i--) {
     var r = Random.Range(0,i);
     var tmp = spawnPoints[i];
     spawnPoints[i] = spawnPoints[r];
     spawnPoints[r] = tmp;
             Transform sp = spawnPoints[r];
             prefabTransforms.Add(Instantiate(spawnThis[i].transform, sp.position , sp.rotation) as Transform);
             print(spawnPoints[r]);        
             }
 
     }
     
     
     }

Now I;m at the second part of the problem. I spawn the objects but I spawn all the objects from the spawnThis list for eact object from spawnPoints list, so I get like 14 times more spawns..

avatar image primus88 · Jun 03, 2013 at 08:18 PM 0
Share

Ok, so I remove the :

 prefabTransforms.Add(Instantiate(spawnThis[i].transform, sp.position , sp.rotation) as Transform);

and call it from where ? How do I call it ? Please help.

avatar image flaviusxvii · Jun 03, 2013 at 08:28 PM 0
Share

@primus88 you need to try to do this yourself. This is not a forum for people to hold your hand every step of the way. If you want to learn this you need to spend at least a few $$anonymous$$utes thinking it through.

avatar image Mahtrok · Jun 03, 2013 at 08:37 PM 0
Share

Try this: it spawns every Object of your array spawnThis once at a unique spawnpoint.

 void Generate () {
      GameObject[] go = GameObject.FindObjectsWithTag ("BattlePointSpawner");
      // Add all BP transforms
      foreach( GameObject BP in go ) {
           AddTarget ( BP.transform );
      }
      // Spawn all objects at a unique spawnpoint and each Object only once
      for ( int i = 0; i < spawnThis.Length; i++) {
           RandomizeBuiltInArray (i);
      }
 }
 
 void AddTarget ( Transform t ) {
      spawnPoints.Add ( t );
 }
 
 void RandomizeBuiltInArray ( int index ) {
      int r = Random.Range(0, spawnPoints.Count-1);
      Instantiate(spawnThis[index], spawnPoints[r].position, spawnPoints[r].rotation) as Transform;
      spawnPoints.RemoveAt(r);
 }
avatar image primus88 · Jun 03, 2013 at 08:42 PM 0
Share

Thank you.

For this line : Instantiate(spawnThis[index].transform, spawnPoints[r].position, spawnPoints[r].rotation) as Transform;

I receive this error :

World$$anonymous$$apRandomizer.cs(75,107): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

Show more comments

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

19 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Spawning Error.. 0 Answers

GetComponentInChildren(Renderer).active wont work? 2 Answers

How to spawn an object with an added force 1 Answer

Make a spawn point 1 Answer


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