C# Script for setting mesh filters and materials

Hello, I’m glad that you’ve read my question. Thank you very much!

My question is about writing a C# script for an empty gameobject.

First, I need to declare multiple Gameobjects , Material , Mesh in each arrays.

public GameObject OBJ = new GameObject[64];

public Material MAR = new Material[64];

public Mesh MESH = new Mesh[64];

Second, I need to set those materials and mesh filters from my project folder.

example that I want to apply is ( * this sample code doesn’t work… )

MAR = Resources.Load(“/Materials/MyMaterial1”);
> MESH = Resources.Load(“/Meshes/MyMesh1”);
Finally, I want to apply those Materials and Meshes to Gameobject “OBJ*” arrays.*
How can I apply those materials amd meshes from script and my project folders?
Thank you for read my questions, I’d be appreciated to solve this problem!

There are a few problems with what you’re doing, but they are easy to remedy. Meshes cannot exist as standalone objects in Unity (though you can generate them from code), if you want to load a mesh of an object you must have a prefab to extract mesh data from. This means you create a prefab, place it in your Resources/Meshes/ folder and then load up the GameObject with Resources.Load(“Meshes/MyMesh1”) for MyMesh1 prefab. After you have the GameObject you can get the mesh from the MeshFilter component.

Materials can be loaded directly from the Resources folder, as long as you specify the type of object as Material. When you create your GameObject from this data you need to initialize the GameObject and add a MeshFilter and MeshRenderer component, then assign your data to these components. Here is some code that will load a material and a mesh object and stick it on a new GameObject.

public void LoadResources()
		//Load material "MaterialTest" and extract mesh from a prefab named "MeshTest"
		Material material = Resources.Load("MaterialTest", typeof(Material)) as Material;
		Mesh mesh = ((GameObject)Resources.Load ("MeshTest")).GetComponent<MeshFilter>().mesh;
		//Instantiate a new game object, and add mesh components so it's visible
		//We set the sharedMesh to the mesh we extracted from the prefab and the material 
		//of the MeshRenderer component
		GameObject go = new GameObject("Test");
		MeshFilter meshFilter = go.AddComponent<MeshFilter>();
		meshFilter.sharedMesh = mesh;
		MeshRenderer meshRenderer = go.AddComponent<MeshRenderer>();
		meshRenderer.material = material;

In unity this will create a new GameObject named “Test” which has the mesh from the prefab “MeshTest” with the material from the “MaterialTest” resource. This new GameObject will be created in the current scene, this may or may not be what you want.

If you aren’t generating the mesh from code, but loading from a prefab, you might get more out of simply instantiating the prefab and assigning it a material.