Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 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 cdalyz · Apr 30, 2019 at 10:14 PM · random.rangeobject pool

Random Object Pooler

Hi all, i have an object pooler script which has multiple objects inside it. i have another script which spawns these objects in order, i wish to make this random but i am really stuck. advice greatly appreciated .... public class FinalObjPool : MonoBehaviour { public static FinalObjPool instance;

 public List<GameObject> pooledObjects;
 public int countToPool = 3;
 public bool canExpand = false;
 void Awake()
 {

     if(instance == null)
     {
         instance = this;
     }

     pooledObjects = new List<GameObject>();
     foreach (GameObject p in platforms)
     {
         for (int i = 0; i < numOfEachHelix; ++i)
         {
             GameObject obj = Instantiate(p);
             obj.SetActive(false);
             pooledObjects.Add(obj);
         }
     }
 }

////// //// i wish to pass a random value in here

 public GameObject GetPooledObject()
 {
     
     for (int i = 0; i < pooledObjects.Count; i++){
         if (!pooledObjects[i].activeInHierarchy)
         {
             return pooledObjects[i];
         }           
     }
     return null;
 }

}

//second script//

public class FinalPlatGen : MonoBehaviour {

 // Update is called once per frame
 void FixedUpdate()
 {
     OnObjectSpawn();
 }

 public Transform genPoint;
 System.Random rand;

 List<int> spawnDegree = new List<int> { 30, 60, 90, 120, 150, 180, 210, 240, 270 };

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

     if (transform.position.y + 5 < genPoint.position.y)
     {
         int RotationValue = Random.Range(0, spawnDegree.Count);
         int randomVal = spawnDegree[RotationValue];
         transform.position = new Vector3(0, transform.position.y + 3, 0);


///i wish to make this part random

         GameObject newPlatform = FinalObjPool.instance.GetPooledObject();


         if (newPlatform == null)
         {
             Debug.Log("NONE");
             return;
         }
         newPlatform.transform.position = transform.position;
         newPlatform.transform.Rotate(0, randomVal, 0);

         newPlatform.transform.SetParent(helix);
         newPlatform.SetActive(true);
     }
 }

}

Comment
Add comment · Show 3
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 MasterChameleonGames · Apr 30, 2019 at 10:19 PM 0
Share

So you want to randomize the angle, but randomVal is returning the same value every time?

avatar image MasterChameleonGames MasterChameleonGames · Apr 30, 2019 at 10:37 PM 0
Share

Ah, the website broke the script, so I couldn't tell if that comment was applied to the entire section or that line following it.

Looks like GetPooledObject() goes through the list in order and finds the first object that hasn't been set active yet.

Ins$$anonymous$$d of that, you could use a while() loop, and inside it, you can have i set to a random number between 0 and pooledObjects.length, and you could check if pooledObjects[i] is active or not. If it isn't, that object can be used.

Also, you can reply to comments

avatar image cdalyz · Apr 30, 2019 at 10:26 PM 0
Share

Hi @$$anonymous$$asterChameleonGames No basically I have 20 game objects, all different. These objects are added to the pool 3 times each. So all together 60 objects. But when spawning from the pool, they spawn in order. I am looking to spawn them randomly, not in any specific order. Tried many different ways but can't get this to work :(

3 Replies

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

Answer by Hellium · Apr 30, 2019 at 10:36 PM

  public GameObject GetPooledObject()
  {
      // Filter the list of pooled object and put all the inactive ones into a new list
      List<GameObject> inactiveObjects = pooledObjects.FindAll( go => !go.activeInHierarchy );

      // Check if the list created above has elements
      // If so, pick a random one,
      // Return null otherwise
      return inactiveObjects.Count > 0 ?
          inactiveObjects[ Random.Range(0, inactiveObjects.Count) ] :
          null;
  }
Comment
Add comment · Show 5 · 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 Captain_Pineapple · Apr 30, 2019 at 10:43 PM 0
Share

Nicely done! I like your solution.

avatar image MasterChameleonGames · Apr 30, 2019 at 10:48 PM 0
Share

Nice, but you might want to explain how it works.

avatar image Hellium MasterChameleonGames · May 01, 2019 at 08:33 AM 0
Share

I believe a code of 4 lines is not that complicated to understand, only the FindAll function can be hard to grasp if you have never encountered it. But anyway, I've commented on the code for better clarity.

avatar image MasterChameleonGames Hellium · May 01, 2019 at 11:18 AM 0
Share

Well, code of any length can be complicated, and besides, it will be easier for the op to understand and possibly use again.

Show more comments
avatar image
1

Answer by Captain_Pineapple · Apr 30, 2019 at 10:41 PM

Hey there,

how about you shuffel your list when you created it? Something along the line:

     List<GameObject> shuffeledList = new List<GameObject>();
     while(pooledObjects.Count > 0)
     {
         shuffeledList.Add(pooledObjects[Random.Range(pooledObjects.Count)]);
     }
     pooledObjects = shuffeledList;

This way you will get the same order of objects but it's not the instantiation order. If this does not work for you, then you have to iterate ovver the whole list, remember the indices that were active and then choose a random value from this list of indices. Another way would be to keep 2 seperate lists, one for active objects, one for inactive. Then you can simply choose any random object from this active list. The latter might even be a bit better on performance.

Let me know what you think or if you need any further information.

Comment
Add comment · Show 1 · 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 cdalyz · May 01, 2019 at 05:33 PM 0
Share

good solution, tried both but @Hellium 's solution was more suited. Thanks for your solution too!

avatar image
0

Answer by Righteousice · Feb 26, 2021 at 09:35 PM

Was having similar issue: public GameObject GetPooledObject() {

  for (int i = 0; i < pooledObjects.Count; i++){
      if (!pooledObjects[i].activeInHierarchy)
      {
          return pooledObjects[i];
      }           
  }
  return null;

}

Use:

public GameObject GetPooledObject() {

  for (int i = 0; i < pooledObjects.Count; i++){
      if (!pooledObjects[i].activeInHierarchy)
      {
          return pooledObjects[Random.Range(i, pooledObjects.Count];
      }           
  }
  return null;

}

This pulled a random pooled object without any issue.

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

109 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 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 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 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 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 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

"Null Object" but it IS there. 2 Answers

Object pulling prefabs that are randomly generating between random points? 0 Answers

Enemy Health Doesnt Increase or Reset 2 Answers

random issue 2 Answers

How to make enemies spawn in random y position? 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