Adding a Meshfilter Mesh via Script?

Adding a Meshfilter Mesh via Script?

How do you add a MeshFilter component with a specific mesh, let's say a Capsule mesh (from Unity default library resources), via C#? I'm this far ...

GameObject obj = new GameObject("Player");
MeshFilter meshFilter = obj.AddComponent<MeshFilter>();
meshFilter.mesh = 

Capsule and other primitive meshes are in the Unity default resources and I know how to assign it in the editor but how do I obtain one in C#? Obviously instantiaion isn't available since it's a library asset.

UPDATE:

I would have thought that this would work:

meshFilter.mesh = Resources.Load<Mesh>("Capsule");

But the mesh is still null afterwards in the editor component inspector.

2

2 Answers

I am not aware about a direct way how to would not know a direct way how to do it, but there is the "hacky" way:

MeshFilter meshfilter = gameObject.AddComponent<MeshFilter>();
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Capsule);
meshfilter.mesh = go.GetComponent<MeshFilter>().mesh;
meshfilter.gameObject.AddComponent<MeshRenderer>();
Destroy(go);

Does that help?

2
GameObject obj=GameObject.CreatePrimitive(PrimitiveType.Capsule);
obj.name="Player";
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.