I want to run a block of code that will check if the gameobject has a mesh attached. The issue is, if there is NO mesh attached, I receive an error.
“MissingComponentException: There is no ‘MeshFilter’ attached to the “Sofa 10” game object, but a script is trying to access it.
You probably need to add a MeshFilter to the game object “Sofa 10”. Or your script needs to check if the component is attached before using it.”
if (this.transform.GetComponent<MeshFilter>().mesh == null)
{
/// create a new mesh
Mesh topLevelmesh = new Mesh();
}
So obviously that is why I’m checking… why do I receive a runtime error, should I do a try catch?
First, there’s no real reason as far as I know to use this.transform.GetComponent instead of just GetComponent
Second, don’t use .mesh. When you use that, Unity tries to access the mesh in MeshFilter, which isn’t attached to the GameObject. Instead, remove .mesh, and Unity will just check if the GameObject has the MeshFilter component
Are you reading the error? The error tells you exactly what is wrong. There is no mesh filter on the ‘Sofa 10’ game Object.
The mesh and the meshFilter are two different things. The mesh is the collection of vertices and faces that describes a shape, the meshFilter is the component that holds the mesh.
var filter = GetComponent<MeshFilter>() ?? gameObject.AddComponent<MeshFilter>(); //gets the mesh filter or creates one if it doesn't exist
if (!filter.mesh) {
var topLevelMesh = new Mesh();
// ~ code that creates your top level mesh
filter.mesh = topLevelMesh;
}
I just tried it for myself, it didn’t work for me either.
?? is called the ‘null coalescing operator’.
If the left hand operand evaluates to null, it takes the right hand operand instead. I’m not entirely sure why it’s not working in this case, but I imagine it either has something to do with Unity’s serialization or the Component bool operator overload. Maybe C# sees that GetComponent() is equating to false instead of null, and that’s why we don’t get to the other operand.
ANYWAY, use this instead:
var filter = GetComponent<MeshFilter>();
if (!filter)
filter = gameObject.AddComponent<MeshFilter>();
if (!filter.mesh)
{
Debug.Log("Null Mesh");
Mesh topLevelmesh = new Mesh();
Debug.Log(topLevelmesh.vertices);
filter.mesh = topLevelmesh;
}