jonesmax
jonesmax

Reputation: 95

How do I set a material to an gameobject in unity c# script?

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.

Upvotes: 6

Views: 26168

Answers (3)

Poly
Poly

Reputation: 1

you have to put something in resources folder , and took it by it s name as the Unity documentation says https://docs.unity3d.com/ScriptReference/Resources.Load.html

Upvotes: 0

Pac0
Pac0

Reputation: 23174

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;

Upvotes: 7

Chopi
Chopi

Reputation: 1143

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.

Upvotes: 3

Related Questions