3
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ Do you want to change the material or a property from the assigned material ? \$\endgroup\$
    – Raxvan
    Commented 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\$ Commented 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
    Commented Sep 29, 2014 at 15:44

2 Answers 2

3
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$
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++;
    }
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Why would you repeat yourself at the bottom there, retyping the same code except for a number, instead of just using i as the array index and writing this code just once? \$\endgroup\$
    – DMGregory
    Commented Jul 27, 2019 at 11:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .