- Home /
Assets/SkyAir.cs(13,25): error CS0029: Cannot implicitly convert type `UnityEngine.GameObject[]' to `UnityEngine.Object'
I get the error above from the script below, I sort of understand the problem, basically it won't let me assign a GameObject to a variable that's an array/table. What I don't understand is why I'm getting the error, somewhere in there it should get converted shouldn't it? I literally copied and pasted the code from this page: http://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html And then I changed the names on the variables and the tag so it actually fits in with my stuff. Help please. Thank you. :)
Alternatively if there's another way to compose a table/list/array (I don't really know what it's properly called in C# in Unity), I could do that. my end goal is to have the list called voxels
to contain every GameObject with the tag "TerrainVoxel".
using UnityEngine;
using System.Collections;
public class SkyAir : MonoBehaviour {
public GameObject Air;
public GameObject VoxelTerrain;
public Object voxels;
// Use this for initialization
void Start () {
if (voxels == null)
voxels = GameObject.FindGameObjectsWithTag("TerrainVoxel");
foreach (Object voxel in voxels) {
if (voxel.transform.position.y >= 513) {
Instantiate (Air, voxel.transform.position, voxel.transform.rotation);
Destroy (voxel);
}
}
}
// Update is called once per frame
void Update () {
}
}
Answer by NoseKills · Mar 26, 2015 at 08:06 AM
You have to stay true to your variable types. FindGameObjectsWithTag() returns an array of GameObjects. You can't put an array into a UnityEngine.Object variable.
Even if you could, on the next line, how could the compiler know that this 'object' you create is something you can loop with a foreach?
Even if it did, inside the foreach loop, a UnityEngine.Object does not have a variable 'transform', so voxel.transform won't work either.
You have to declare 'voxels' a GameObject[] and 'voxel' a GameObject
Thanks, doing what you suggested did solve the issue. However, I'm still confused as to why Unity's documentation would have had an example that didn't work. Though, if you don't know, don't worry about it.
Answer by MakakWasTaken · Mar 26, 2015 at 03:11 PM
Try with this instead: public GameObject Air; public GameObject VoxelTerrain; public GameObject[] voxels;
// Use this for initialization
void Start () {
if (voxels == null)
voxels = GameObject.FindGameObjectsWithTag("TerrainVoxel");
foreach (GameObject voxel in voxels) {
if (voxel.transform.position.y >= 513) {
GameObjet.Instantiate (Air, voxel.transform.position, voxel.transform.rotation);
Destroy (voxel);
}
}
}