Cannot add Mesh via script

Hi there! I want to add a Mesh to Mesh Collider of an object. I’m trying the code below:

        GameObject headd = Resources.Load("Art/Prefabs/head") as GameObject;
        headd.name = "heaed";
        GameObject head = Instantiate(headd);
        head.transform.rotation = Quaternion.Euler(0.0f, 180.0f, 0.0f);
        Destroy(head.GetComponent<SphereCollider>());
        head.AddComponent<MeshRenderer>();
        head.AddComponent<MeshCollider>();
        head.GetComponent<MeshRenderer>().material = AssetDatabase.GetBuiltinExtraResource<Material>("Default-Diffuse.mat");
        head.GetComponent<MeshCollider>().sharedMesh = Resources.Load<GameObject>("Art/Prefabs/head").GetComponent<Mesh>();
        head.name = "Model";
        head.transform.SetParent(headGO.transform);

When I run the scene, the Mesh Collider’s mesh is still shown as “None” like this.

That part of code:

Resources.Load<GameObject>("Art/Prefabs/head").GetComponent<Mesh>();

returns null. I could not understand why it behaves like this. I have to get Mesh from the .obj file which located in that location.

Also, this is the folder hierarchy of the project which I want to load object and objects mesh from…
186362-screenshot-2021-09-17-141314.png

Thanks…

Hi, @kiryu_kazuma123.

The answer is very simple.

In order to get a mesh from an .obj file, you need to refer to its child object and request the MeshFilter component from it.

For example like this:

var meshFilter = Resources.Load<GameObject>("Art/Prefabs/head").GetComponentInChildren<MeshFilter>();
GetComponent<MeshCollider>().sharedMesh = meshFilter.sharedMesh;