- Home /
Detect if object is a cube(find the primitive type) with physics.raycast
I am making a 3d puzzle game with picking up and placing cubes. I want to only be able to place a cube on a cube. I am using Physics.Raycast to determine where to place the cube. Is there a function I could use to determine the primitive type of the object hit with the Raycast?
Answer by Eric5h5 · Jul 21, 2013 at 11:24 PM
"Primitives" in Unity are really just arbitrary meshes, so they have no inherent value saying whether they are a cube, sphere, etc. You can write a script where you indicate the type yourself and attach it to the objects, such as
var primitiveType : PrimitiveType;
Then use GetComponent on the object hit with the raycast to read the primitiveType variable.
so how would i state the getcomponent? primitiveType = hit.transform.gameObject.GetComponent(PrimitiveType);
or what?
No, the idea is to save that single line as a script ("ObjectType.js", for instance) and attach it to every object you must identify, then set its value in the Inspector. When hitting an object, get its script ObjectType and verify whether its type is a cube - for instance:
var objType: ObjectType = hit.GetComponent(ObjectType);
if (objType){ // if object has ObjectType script...
switch(objType.primitiveType){ // read the type assigned
case PrimitiveType.Cube:
// it's a cube
break;
case PrimitiveType.Sphere:
// it's a sphere
break;
}
}
Notice that you must add the script ObjectType to every object you want to identify, and manually set the type in the Inspector.
Answer by aldonaletto · Jul 21, 2013 at 11:35 PM
You could use the mesh name to identify the primitive type - in this case, it's "Cube Instance":
...
var hit: RaycastHit;
if (Physics.Raycast(ray, hit)){
var mesh: Mesh = hit.gameObject.GetComponent(MeshFilter).mesh;
if (mesh.name == "Cube Instance"){
// object hit is a primitive cube
}
}
...
But this isn't a good solution: the primitive mesh name could change in future Unity versions and make your game useless. A better (and faster) alternative would be to tag the cubes with a specific tag - like "Cube", for instance:
...
var hit: RaycastHit;
if (Physics.Raycast(ray, hit)){
if (hit.gameObject.CompareTag("Cube")){
// object hit is tagged "Cube"
}
}
...
NOTE: Remember to register the tags in the Tag/Layer Manager!
Your answer
Follow this Question
Related Questions
Primitive Cube in code! 0 Answers
Primitive Cube Texturing Help 3 Answers
Texture Problem on Cube primitive 1 Answer
How i can create a cube with specific coordenates? 3 Answers
create primitive cube a runtime with specific size 3 Answers