Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

unity3d

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.

like image 908
jonesmax Avatar asked Apr 15 '18 19:04

jonesmax


2 Answers

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;
like image 55
Pac0 Avatar answered Oct 27 '22 18:10

Pac0


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.

like image 31
Chopi Avatar answered Oct 27 '22 18:10

Chopi