I am attempting to set a material to a game object in my game, I created the object in script so I dont have the option to set it manually through unity. All of this has to be in script etc. my code is
void Start()
{
GameObject cube2 = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube2.transform.position = new Vector3(12f, -3f, -82.5f);
}
So I set the cube I created to "cube2". So aka what I am attempting to do is set it to red. I currently have a material created named red. Thank you.
First, you have to get a reference to your material. Either you use a public variable public Material yourMaterial;
on your component and use drag-and-drop the material in the interface, or you can get it by code like this :
// in the Start() method
Material yourMaterial = Resources.Load("red", typeof(Material)) as Material;
Then, you can assign it to a GameObject with the renderer.material
field :
cube2.renderer.material = yourMaterial;
N.B. :
I'm getting old... .renderer
is obsolete, and one should use .GetComponent<Renderer>()
instead as @Chopi suggests.
Edit :
For Resources.Load
to work, your material red.mat
must be in a Resources
folder. If it is in a subfolder like 'Resources/materials/red.mat', then this would lead to :
Material yourMaterial = Resources.Load("materials/red", typeof(Material)) as Material;
You can set it from code using a public variable
public Material myMaterial;
void Start()
{
GameObject cube2 = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube2.transform.position = new Vector3(12f, -3f, -82.5f);
cube2.GetComponent<Renderer>().material = myMaterial;
}
As Pac0 said you can also use Resource.Load
to avoid using a public variable, but in that case you will need to store your material inside the "Resources" folder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With