How to change material of the active object?

Hi, im using a script that changes material of the object when a key is press. The problem is that i have the same object many times in the same scene(its a prefab that cudnt be changed). I need the script to change just the object prefab im using at the moment. Any ideas?

var myMaterials : Material[];
var NextMaterial : int = 0;
function NextMaterialUsed()
{
renderer.sharedMaterial = myMaterials[NextMaterial];
if(NextMaterial < myMaterials.length-1)
NextMaterial += 1;
else
NextMaterial = 0;
}
 
function Update ()
{
if(Input.GetButtonDown("Jump"))
{
NextMaterialUsed();
}
 
 
}

Don’t set sharedMaterial, if you change that, it’ll change that material’s settings in your project even if only done during a play test in the Editor. Use renderer.material during play. That will also only modify the material for the given object only.

Just in case you (or someone else reading this) is trying to assign materials through code, to make your renderer’s material unique so modifying it won’t affect other objects, do this:

renderer.material = new Material(someCustomMaterial);

Using new Material(someMaterialVariable) will create a completely new, separate material that copies the settings of someMaterialVariable exactly. This is handy to know if you’re assigning the same material to several objects via code, and want it to be able to be tweaked separately per object. After (and only after!) using the line above, you can safely use renderer.material to modify the material’s settings. As an example:

var someMaterial : Material;

function Awake() {
    //create an instance of your renderer's material here
    renderer.material = new Material(someMaterial);
}

function Update() {
    //Modify a setting for renderer.material over time.
    //Notice that same setting won't change for other materials.
    var offset : float = Time.time * scrollSpeed;
    renderer.material.mainTextureOffset = Vector2 (offset, 0);
}