Alright, now this intrigues me. I’ve put the following line of code into a Start function on a CS script, and it gives out null even though I have several objects in scene with the component voxel.
voxels = GameObject.FindObjectsOfType (typeof (voxel)) as GameObject[];
I guess its obvious I’m doing something wrong here, but the console doesn’t debug anything but the NullReferenceExceptions a few lines ahead. Can anyone help? I need to get this to work since it’s a key feature of my game and there aren’t many free voxel engines out there that work with Unity 5.
PS.: I’ve tried Cubiquity but it doesn’t have Unity 5 support sadly, and all other voxel terrain stuff I’ve seen out there usually cost more than 60 dollars which is currently out of my reach.
FindObjectsOfType is inherited from type “Object” and returns an Object - not a GameObject. Even if all members of the array happen to be GameObject’s, that is still an array of Object’s.(1)
What you are doing with the “as GameObject” is to tell the compiler “if the value is an GameObject array, assign it. Otherwise assign null.”
To get an voxel array directly, you can use the generic version of FindObjectsOfType:
However, in your example you are asking for all GameObjects that have a “voxel” component, right? (In other words, “voxels” is of type GameObject not of type voxel).
So you could either change your code so that “voxels” is of type “voxel” and use the generic version above. Or you first fetch the array of voxels and then retrieve all gameObjects that belong to this array:
voxel[] allVoxels = GameObject.FindObjectsOfType<voxel>();
voxels = new GameObject[allVoxels.Length];
for (int i = 0; i < voxels.Length; i++)
voxels _= allVoxels*.gameObject;*_
Or shorter using LINQ - if you include an “using System.Linq;” at the top: voxels = (from v in GameObject.FindObjectsOfType() select v.gameObject).ToArray(); (But don’t get too attached to LINQ. It allocates a lot of unnecessary memory which the Mono GC really hates…) ---------- 1) You can do more things with an Object[] array than you can do with a GameObject[] array. For example, you can assign a non-GameObject to the former and not to the latter. The other way around would work: Every GameObject[] array IS actually also an Object[] array. That is a difference to the generic List where List is NOT convertible into List. Its confusing, I know.