Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
1 capture
11 Jun 22 - 11 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 /
This question was closed Jan 22, 2016 at 07:47 PM by Fattie for the following reason:

http://answers.unity3d.com/answers/733688/view.html

avatar image
1
Question by C___ · Jul 06, 2015 at 07:05 PM · c#errorprefabnullreferenceexceptionresources.loadall

how to CORRECTLY load all assets (using Resources.LoadAll)

so i've been trying to load all my prefab assets found in the Resources/Levels folder using different ways but I get casting problems.

Comment
Add comment · Show 1
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 Fattie · Jan 22, 2016 at 07:47 PM 1
Share

Duplicate of http://answers.unity3d.com/answers/733688/view.html

1 Reply

  • Sort: 
avatar image
11
Best Answer

Answer by ThePunisher · Aug 07, 2015 at 07:37 PM

Hey,

The assumption is that you have a folder named "Levels" inside some Resources folder in your project, because if you don't then the load call will obviously fail. I put together a script based on those methods of loading you provided and tested them out myself just to make sure they behaved as I excepted.

 using UnityEngine;
 using System.Collections;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 
 public class LoadAllTest : MonoBehaviour
 {
     private void Awake()
     {
         // Method #1: Incorrect casting results in InvalidCastException. ==============================================================
         try
         {
             Debug.Log("Loading with Method #1...");
             GameObject[] loadedObjects = (GameObject[])Resources.LoadAll("GameObjects");
 
             foreach(var go in loadedObjects)
             {
                 Debug.Log(go.name);
             }
         }
         catch(Exception e)
         {
             Debug.Log("Method #1 failed with the following exception: ");
             Debug.Log(e);
         }
 
         // Method #2: Incorrect casting results in array of null objects. ====================================
         try
         {
             Debug.Log("Loading with Method #2...");
             GameObject[] loadedObjects = Resources.LoadAll("GameObjects") as GameObject[];
 
             foreach (var go in loadedObjects)
             {
                 Debug.Log(go.name);
             }
         }
         catch (Exception e)
         {
             Debug.Log("Method #2 failed with the following exception: ");
             Debug.Log(e);
         }
 
         // Method #3: Incorrect casting results in array of null objects. ====================================
         try
         {
             Debug.Log("Loading with Method #3...");
             GameObject[] loadedObjects = Resources.LoadAll("GameObjects", typeof(GameObject)) as GameObject[];
 
             foreach (var go in loadedObjects)
             {
                 Debug.Log(go.name);
             }
         }
         catch (Exception e)
         {
             Debug.Log("Method #3 failed with the following exception: ");
             Debug.Log(e);
         }
 
         // Method #4: Incorrect casting results in InvalidCastException. ====================================
         try
         {
             Debug.Log("Loading with Method #4...");
             GameObject[] loadedObjects = (GameObject[])Resources.LoadAll("GameObjects", typeof(GameObject));
 
             foreach (var go in loadedObjects)
             {
                 Debug.Log(go.name);
             }
         }
         catch (Exception e)
         {
             Debug.Log("Method #4 failed with the following exception: ");
             Debug.Log(e);
         }
 
         // Method #5: DOUBLE KILL! Please don't ever do this. I fear the world may implode. ====================================
         try
         {
             Debug.Log("Loading with Method #5...");
             GameObject[] loadedObjects = (GameObject[])Resources.LoadAll("GameObjects", typeof(GameObject)) as GameObject[];
 
             foreach (var go in loadedObjects)
             {
                 Debug.Log(go.name);
             }
         }
         catch (Exception e)
         {
             Debug.Log("Method #5 failed with the following exception: ");
             Debug.Log(e);
         }
 
         // Proper Method: Casting correctly for expected type of loaded objects results in a valid list of loaded objects. ============
         try
         {
             Debug.Log("Loading with Proper Method...");
 
             // This is the short hand version and requires that you include the "using System.Linq;" at the top of the file.
             var loadedObjects = Resources.LoadAll("GameObjects", typeof(GameObject)).Cast<GameObject>();
             foreach(var go in loadedObjects)
             {
                 Debug.Log(go.name);
             }
 
             // Casts each individual UnityEngine.Object into UnityEngine.GameObject and adds it to an actual list of GameObject type. 
             // This one works too but is the long version.
 
             //var loadedObjects = Resources.LoadAll("GameObjects");
             //List<GameObject> gameObjects = new List<GameObject>();
             //foreach (var loadedObject in loadedObjects)
             //{
             //    gameObjects.Add(loadedObject as GameObject);
             //}
 
             //foreach (GameObject go in gameObjects)
             //{
             //    Debug.Log(go.name);
             //}
         }
         catch (Exception e)
         {
             Debug.Log("Proper Method failed with the following exception: ");
             Debug.Log(e);
         }
 
         // ================================================== THOUGHTS =====================================================
 
         // I would never use this variation because it makes a MASSIVE assumption that all assets inside of the specified folder 
         // are actually GameObjects. If someone down the road places a material (or any non-prefab type) in this folder it will 
         // now cause it to fail loading, because those aren't GameObjects, and it will not be apparent at all.
         Resources.LoadAll("GameObjects");
 
         // This variation is preferred as specifying "typeof(YourType)" ensures only assets of type "YourType" get loaded.
         // This is essential if you are casting the loaded assets into a specified type.
         Resources.LoadAll("GameObjects", typeof(GameObject));
     }
 }
 


Comment
Add comment · Show 4 · 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 C___ · Aug 10, 2015 at 05:31 AM 1
Share

neat. thanks for your answer

avatar image ThePunisher · Aug 10, 2015 at 05:17 PM 0
Share

You're welcome! Glad I could help.

avatar image ComeSweetDeath ThePunisher · Nov 16, 2015 at 06:53 AM 0
Share

Thank you!

avatar image jister · Jul 18, 2017 at 08:33 AM 1
Share

Then why do the docs say "textures = Resources.LoadAll("Textures", typeof(Texture2D));" if it clearly is not working?

Follow this Question

Answers Answers and Comments

6 People are following this question.

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

Related Questions

NullReferenceException problem 2 Answers

Unknown reason for NullReferenceException error 1 Answer

NullReferenceException 1 Answer

How can I make this GameObjects array remain permanent when i activate? 1 Answer

NullReferenceException: Object reference not set to an instance of an object DestroyByContact.OnCollisionEnter2D (UnityEngine.Collision2D coll) 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