How do I find the entire Cube object in the scene?
I am looking for a way to find all CubeGameObjects in a scene. I am trying to do this:
Cube[] ballsUp = FindObjectsOfType (typeof(Cube)) as Cube[];
But the cube is not a type of game object.
I think I need to use something related to PrimitiveType, but can figure out what and how to use it ...
thank
source to share
Your cube is of primitive type. And objects of primitive type cannot be found using findobjectsoftype . There are many ways to solve the above problem. The easiest way is to use tags. When you instantiate a cube object, you can use the "Cube" tag.
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.tag = "Cube";
Then you can get all the cube objects in the cube tagged scene using
GameObject[] arrayofcubes = GameObject.FindGameObjectsWithTag("Cube");
This will give the entire array of GameObject cubes in the scene.
FindObjectsOfType can be used to find game objects with attached classified rather than primitive types.
Another way to proceed is to find all objects using MeshFilters and Find the searched 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);
}
}
}
source to share
You can try this. If you are using a unit cube primitive, the mesh should be named "Cube" when running "Cube Instance".
var gameOjects = GameObject.FindObjectsOfType<GameObject>();
foreach (var gameOject in gameOjects)
{
var meshFilter = gameOject.GetComponent<MeshFilter>();
if (meshFilter != null && meshFilter.mesh.name == "Cube Instance")
Debug.Log(gameOject.name);
}
Tough, it's not very elegant or robust.
A more suitable way would be to tag all cubes and get them with "FindGameObjectsWithTag"
source to share
It is then recommended to use Unity to create the tag and then use GameObject.FindGameObjectsWithTag
to find all of them. GameObject.FindGameObjectsWithTag
returns an array of objects in this tag.
For example, create a tag called "cubeTags", then go to each cube and replace the tag with cubeTags. When you want to find all cubes, you can simply do:
GameObject[] cubes = GameObject.FindGameObjectsWithTag ("cubeTags");
Cube[] ballsUp = new Cube[cubes.Length];
for(int i=0; i<cubes.Length; i++){
ballsUp = cubes[i].GetComponent<Cube>();
}
source to share