Reputation: 9586
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.
Upvotes: 1
Views: 10734
Reputation:
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?
Upvotes: 6
Reputation: 4061
GameObject obj=GameObject.CreatePrimitive(PrimitiveType.Capsule);
obj.name="Player";
Upvotes: 0