- Home /
How to change material of gameobject using C# to a material asset.
I have a square gameobject with a script attached to it in my scene. This gameobject already has a material component called matOne attached to it.
When it's hit by an object, I need the square to change it's material to matTwo, which is inside my project assets folder. I have absolutely no idea on how to do this.
void OnCollisionEnter(Collision col)
{
if (brickType == BrickType.Grass)
{
brickType = BrickType.Dirt;
// Code that changes the mesh to a mesh in my assets.
hitPoints = hitPoints - takeDamage;
hitPoints = hitPoints - 1;
}
}
My guess is that I need to use:
gameObject.GetComponent<MeshRenderer>().material //some more code
and
Resources.Load //some more code
But that's all I managed to extract from various other questions and the official documentation.
public $$anonymous$$aterial redBox; //place at top of script and assign the material in the editor this.GetComponent().material = redBox; I think you have the answer already.... So maybe I am missing something
Answer by Sisso · Apr 23, 2014 at 03:15 PM
Simple read the docs and look its examples
https://docs.unity3d.com/Documentation/ScriptReference/Renderer-material.html
https://docs.unity3d.com/Documentation/ScriptReference/Resources.html
If you didn't understand something in the docs, please ask.
Answer by FrikFrac · Jul 31, 2016 at 04:40 AM
public Renderer screen;
public Material unLockedMat;
void LazerDeactivation()
{
lazer.SetActive(false);
screen.material = unLockedMat;
GetComponent<AudioSource>().Play();
}
I had same problem I created a public Renderer variable for the screen and for the material. It works but remember the Renderer must be the exact object which contains the material you wish to change not the parent object.
I hope this helps.