- Home /
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...
Thanks....
Please edit your question and provide a screenshot of the head object in your Project tab.
Keep in $$anonymous$$d that Resources.Load
looks for assets in a subfolder of a Resources
folder.
Yeah I know, I added the screenshot which shows the path I want to load it from, the problem is not the path I think...
Answer by tonaros1 · Sep 17, 2021 at 12:17 PM
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;
Your answer
![](https://koobas.hobune.stream/wayback/20220613043131im_/https://answers.unity.com/themes/thub/images/avi.jpg)