I was making a game with Unity and I want to change an object's material using UnityScript when the player collects 5 collectables that I made. The collectables get stored in an int variable called Score.
-
\$\begingroup\$ Do you want to change the material or a property from the assigned material ? \$\endgroup\$Raxvan– Raxvan2014-09-29 15:40:46 +00:00Commented Sep 29, 2014 at 15:40
-
\$\begingroup\$ The material.Like the texture thing on top of an game object.Those files stored as .mat . \$\endgroup\$ElPolloLoco999– ElPolloLoco9992014-09-29 15:41:44 +00:00Commented Sep 29, 2014 at 15:41
-
\$\begingroup\$ in C#: gameObject.GetComponent<MeshRenderer>().material.mainTexture = new_texture; the "Javascript" code should be similar to this. \$\endgroup\$Raxvan– Raxvan2014-09-29 15:44:38 +00:00Commented Sep 29, 2014 at 15:44
2 Answers
If you want to change a Material in Unity you have to retrieve it first.
If your GameObject uses a Material it means that it uses a Renderer.
You can retrieve your object renderer using the internal variable renderer or get it using the GetComponent function. On the renderer object you will find a material property containing the active Material.
For example:
MeshRenderer my_renderer = GetComponent<MeshRenderer>();
if ( my_renderer != null )
{
Material my_material = my_renderer.material;
}
If you want to change the current material, you can use the same access. For example:
my_renderer.material = other_material;
I suggest to make other_material a public Material variable of your game object. However if you want to load it at runtime you should have a look at Resources.Load.
I hope it helps.
public Material[] mainMat;
Renderer rend;
public static int index;
public static int i;
public void Start()
{
rend = GetComponent<Renderer> ();
rend.enabled = true;
// rend.sharedMaterial = mainMat [0];
}
public void changeMat()
{
if (i == 0) {
rend.sharedMaterial = mainMat [0];
i++;
}
else if (i == 1)
{
rend.sharedMaterial = mainMat [1];
i++;
}
-
1\$\begingroup\$ Why would you repeat yourself at the bottom there, retyping the same code except for a number, instead of just using
ias the array index and writing this code just once? \$\endgroup\$2019-07-27 11:32:10 +00:00Commented Jul 27, 2019 at 11:32