I have created a single mesh sphere, with 4 submesh,
and I have created 3 buttons, which I need to change the submesh materials.
but when pressing each button, it changes ALL the material mesh.
and I only need to change one of the four materials that the mesh contains
that’s why the question:
how to change only one submesh material on a single object ?
i attach here a small video,
a unitypackage 0.2 MB size, to download
and the code.
please help, i will apreciate so much any help or comment.
thanks
.
using UnityEngine;
public class changematerial : MonoBehaviour {
public Material Material1;
public Material Material2;
public Material Material3;
//in the editor this is what you would set as the object you wan't to change
public GameObject Object;
public void touch_cube_mat_1()
{ Object.GetComponent<MeshRenderer> ().material = Material1;
Debug.Log("render mat 1"); }
public void touch_cube_mat_2()
{ Object.GetComponent<MeshRenderer> ().material = Material2;
Debug.Log("render mat 2"); }
public void touch_cube_mat_3()
{ Object.GetComponent<MeshRenderer> ().material = Material3;
Debug.Log("render mat 3"); }
}
It’s only changing the first one because Renderer.material will always return the first material in the material array. You need to use Renderer.material_s_ and access them based on their index.
thansk … really thanks …
that link solve this with this :
Note that like all arrays returned by Unity, this returns a copy of materials array. If you want to change some materials in it, get the value, change an entry and set materials back.
but i dont know how to do it, i know C# basics … please any code idea how to do this please.
i will pareciate so much.
please ?
//a new script
Material myMaterialReplacement;
Material[] sharedMaterials;
Renderer rend;
private void Start()
{
rend = GetComponent<Renderer>();
sharedMaterials = rend.sharedMaterials;
}
// lets assume this method is running from a button click
private void Button_ChangeMaterial()
{
// assume you want to change material index 0
// these 'indexes' can be found in the renderer on your object as the order of the materials;
int materialIndex = 0;
sharedMaterials[materialIndex] = myMaterialReplacement;
rend.sharedMaterials = sharedMaterials;
}
ok … my report !!!
all work great … but
when i add animation to the sphere … LOST THE MESH RENDER COMPONENT
so i add it again …
but now … only change the material of the mesh render and not change the SKIN MESH RENDER…
now the new quation is please … how can i change the SKIN MESH RENDER (read arror on next picture)
i apreciate so much any comment
.