- Home /
Resources.LoadAll(); GameObject[] Array
Here is my question:
using UnityEngine;
using System.Collections;
public class Hajawack : MonoBehaviour {
GameObject[] objMatToCompTo;
// Use this for initialization
void Start () {
objMatToCompTo = Resources.LoadAll("(1)BlockPreFab", typeof(GameObject)) as GameObject[];
}
// Update is called once per frame
void Update () {
Debug.Log(objMatToCompTo[0].name);
}
}
Debug.Log, instead of printing, gives me the error:
NullReferenceException: Object reference not set to an instance of an object
What should i do?
This is really odd... Please, i really need some help, im working on this till now, and didnt found it by myself... $$anonymous$$aybe something like:
http://answers.unity3d.com/questions/292745/how-do-i-create-instatiate-an-array-of-gameobjects.html
I really dont know...
Answer by ArkaneX · Oct 04, 2013 at 07:54 AM
Assuming you have folder (1)BlockPreFab under Assets\\Resources, then Resources.LoadAll
probably works ok, but converting result messes things up. You can't convert Object[] to GameObject[]. You have to do your casting differently, for example using LINQ:
objMatToCompTo = Resources.LoadAll("(1)BlockPreFab", typeof(GameObject))
.Cast<GameObject>()
.ToArray();
Additionally you need to add
using System.Linq;
on top of your script.
Thank you so much! This is tricky, but I would assume a pretty common thing to need to be done
You can just use this syntax:
GameObject[] obj$$anonymous$$atToCompTo;
obj$$anonymous$$atToCompTo = Resources.LoadAll<GameObject>("(1)BlockPreFab");
yes, but be aware that then you have to cast each one each time you use it
Thank you very much for this. I tried about 15 other suggestions which all failed before I found this. Thanks!
Your answer
Follow this Question
Related Questions
Using Resources.LoadAll with arrays 1 Answer
Making 'table' (2D built-in array) of GameObjects giving "NullReferenceException:" error 1 Answer
NullReferenceException error in an array of objects 0 Answers
Save Multiple GameObject with XML 1 Answer
Don't see the cause of this NullReferenceException... 1 Answer