Search code examples
unity-game-enginegameobject

How to find all Cube game Object in the scene?


I'm looking for a way to find all CubeGameObject in the scene. I'm trying to do this :

Cube[] ballsUp = FindObjectsOfType (typeof(Cube)) as Cube[];

But cube isn't a game object type apparently.

I think i need to use something related to PrimitiveType but can figure out what and how to use it...

Thanks


Solution

  • Your Cube is of primitive type. And Primitive type objects are not possible to find using FindObjectsOfType. There are many ways to solve the above problem. The easiest is by using tags. When you instantiate your cube object you can use tag "Cube".

    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        cube.tag = "Cube";
    

    Then you can get all the cube objects in scene with cube tags using

    GameObject[] arrayofcubes = GameObject.FindGameObjectsWithTag("Cube");
    

    This will give all the array of GameObject cubes in the scene.

    FindObjectsOfType can be used to find gameobjects with attached classed and not primitive types.

    Another way to proceed is finding all objects with MeshFilters and Searching for the Desired primitive name in the mesh filter arrays

    string[] meshNames = new string[5] {"Cube", "Sphere", "Capsule", "Cylinder", "Plane"};
    MeshFilter[] allMeshFilters = FindObjectsOfType(typeof(MeshFilter)) as MeshFilter[];
    foreach(MeshFilter thisMeshFilter in allMeshFilters)
    {       
        foreach(string primName in meshNames)
        {           
            if (primName == thisMeshFilter.sharedMesh.name)
            {
                Debug.Log("Found a primitive of type: " + primName);                
            }           
        }       
    }
    

    Geeting all the Object by their primitive type (C#)