How do I access variables of prefabs I am loading via Resource.LoadAll, in script(C#)

I am having trouble retrieving variable information on some prefabs I am loading via resource.loadall.

I have a class called Tile that I have applied to some quad prefabs I have made in Unity, in it I have a few variables like displayName. They are public, and for each prefab I made and have in a resource folder I have a Display Name I have set in the Inspector.

I have these quads generating a tiled map, I basically use Resource.LoadAll to put all of the prefab tiles into an Object array, like so:

Object[] prefabarray = Resources.LoadAll ("PrefabTiles/Primary", typeof(GameObject));

Just after this, I randomly pick one and have it instantiated into particular position, but before that I would like to retrieve or test what Display Name that random tile has, but when I try this:

Debug.Log (prefabarray[0].displayName);

I get an error, and that var does not exist for that object. I am presuming I am missing a cast or something(you can see I am casting it as a GameObject above, don’t know if that is correct, but debug.log tells me it IS a GameObject).

In game though, when I mouse-enter a certain tile, it will spit out displayName(I have it set up to do that). So in script I am just unable to get that info.

Any help is greatly appreciated, thanks in advance.

you have to use getComponent

Debug.Log (prefabarray[0].GetComponent<ScriptName>.displayName);

As you are saying displayName is not a variable of Object, but a variable of Tile. So you need to cast your list to another type. In the Resources.LoadAll you are not actually casting to GameObject, but you are telling it to load all GameObjects, the list returned will still be a Object list. To cast the list to GameObject you can do this:

GameObject[] prefabArray = Resources.LoadAll("PrefabTiles/Primary", typeof(GameObject)) as GameObject[];

Notice I changed the type of the list as well as casting after the Resources.LoadAll function.

We still need to get a hold of displayname which is in the Tile component on those GameObjects. You can get a hold of components on GameObjects with the GetComponent function:

Debug.Log (prefabarray[0].GetComponent<Tile>().displayName);

We can change some things around in the load section to make this even easier:

Tile[] prefabArray = Resources.LoadAll("PrefabTiles/Primary", typeof(Tile)) as Tile[];

Here we are telling the function to load all GameObjects with a Tile component on it, we get a Object list then cast it to a Tile list and store it in the Tile prefabArray.

Then you we can do this to access the values:

Debug.Log (prefabarray[0].displayName);