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
1
Question by elmanofsuit · Oct 24, 2014 at 11:38 PM · listsrandomspawningfoldersresources.loadall

Instantiate random prefab from folder using Resources.LoadAll

Resources.LoadAll strikes me as an extremely versatile tool, and on the surface seems fairly easy to implement. However, I'm having a devil of a time putting together a straightforward "fill list with contents of this folder" function without getting some fairly frustrating errors.

I've found a good number of asset-specific solutions (i.e. for textures or sound files), but I'm sure I'm not the only one who would benefit from a straightforward guide on how to manage this with generic GameObjects.

I've tried a number of variations, but the sample below looks clean and straightforward enough to my eyes.

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using System.Linq;
 
 public class RandomFromList : MonoBehaviour 
 {
     public List<GameObject> roomList;
 
     void Start () 
     {
         GenerateRoom ();
     }
 
     void GenerateRoom ()
     {
         roomList = Resources.LoadAll<GameObject>("Rooms");
         GameObject roomToBuild = roomList [Random.Range (0, roomList.Count)];
         GameObject newRoom = Instantiate (roomToBuild, transform.position, Quaternion.identity) as GameObject;
     }
 }

Most of my errors tend to be of the "cannot cast Object as GameObject" variety, implying that the LoadAll function is for some reason using Object data, and requires some (seemingly extraneous) casting to work. However, casting as GameObject and/or working with Objects yields similar errors - frustrating as I'm still trying to wrap my head around when and why Unity chooses to use Object at all.

Added confusion stems from the syntax for declaring and working with lists and arrays. While none of the systems for declaring these should be vastly different from each other, I regularly get error messages wherein Object[] has the array brackets. Since LoadAll seems perfect for lists given their easy resizability, it seems unlikely that the Unity framework would use an array at all in this context - is it just a complication of the [] around where I set the Random.Range (which has worked for me countless times in the past), or is this just a red herring?

"Array index out of range" crops up regularly thanks to the list in question remaining empty. For awhile I wondered if the list length might need to be set before it can be filled, but since I haven't seen this addressed in any of the other questions on this topic, I have to assume it's not the case. Still, worth mentioning just in case.

Again, I'm sure I'm not the only one to have this problem, and am certain there's someone out there with a workable solution they wouldn't mind sharing with the rest of us.

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
1

Answer by tanuj0092 · Oct 25, 2014 at 01:52 PM

Try this code:

  using UnityEngine;
  using System.Collections;
  using System.Collections.Generic;
  using System.Linq;
  
  public class RandomFromList : MonoBehaviour 
  {
      public List<GameObject> roomList;
      
      public GameObject[] roomListArray;
  
      void Start () 
      {
          GenerateRoom ();
      }
  
      void GenerateRoom ()
      {
          //Store all Gameobjects in an array like this
          roomListArray = Resources.LoadAll<GameObject>("Rooms");
 
          //You can use ToList() function as you are using Linq
          roomList = roomListArray.ToList();
 
          GameObject roomToBuild = roomList [Random.Range (0, roomList.Count)];
          GameObject newRoom = Instantiate (roomToBuild, transform.position, Quaternion.identity) as GameObject;
      }
  }

or you can use this reference

http://docs.unity3d.com/ScriptReference/Resources.LoadAll.html

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 tanuj0092 · Oct 25, 2014 at 01:53 PM 0
Share

However you can avoid ToList() conversion. You can play around array :)

avatar image elmanofsuit · Oct 25, 2014 at 07:02 PM 0
Share

That does not help. The conversion of a list into an array does indeed seem extraneous (and works no better), and using an array gives an invalid argument (float, float) error for Random.Range. Not sure why, as Random.Range can pick random objects off of a list no problem.

And please, give me a little credit. Script Reference is the first thing I checked, I wouldn't be posting here if the solution could be found there.

avatar image tanuj0092 · Oct 26, 2014 at 01:51 PM 0
Share

Hey, I did a little workaround on this code, I have edited the code as you cannot cast Object[] to GameObject[] directly. So, I put three prefabs in Rooms folder inside Resources folder in project window. I attached the script to an empty gameobject. And in this way I was able to instantiate the random object in the scene. Also, I named the objects randomly. I hope this would give you some help.

avatar image
0

Answer by elmanofsuit · Oct 27, 2014 at 11:55 PM

Ah, figured it out. Turns out I had been (sometimes) casting correctly, but hadn't placed my folder inside of one called "Resources." Not sure why Unity never gave a "path not found" error, that could have certainly set me on the right track.

Technically that info is all in the Script Reference, but the way it's worded is a little unclear. I suppose some re-reading and guesswork could have saved me a lot of trouble, but at least this is a mistake I sure won't make again.

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Comparing Vector 3 position to a list of vector 3 positions 0 Answers

Resources.LoadAll on Current Folder Only? 1 Answer

Load all Json Files from Resources into a converted list? 3 Answers

List inside of a list in a custom window 0 Answers

Making if statement inside of findAll 2 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