- Home /
Changing material on SkinnedMeshRenderer changes on other objects too
I have written a script that you can attach to a GameObject and it will allow you to hover over it and change the material to one with a different shader.
Here it is:
public Material normal;
public Material highLight;
private new SkinnedMeshRenderer renderer;
private void Start() {
renderer = transform.GetComponentInChildren<SkinnedMeshRenderer>();
}
private void Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100)) {
if (hit.transform.gameObject.tag == transform.gameObject.tag) {
renderer.material = normal;
}
if (hit.transform.gameObject.tag != transform.gameObject.tag) {
renderer.material = highLight;
}
}
}
I'm using this to highlight when a player hover over an enemy and these two enemies share a similar mesh. So, when I hover over one the other enemy is also highlighted.
How do Is stop this from happening?
same material will be using other objects so make a new material and assign texture then apply new material on the object.
assigning a value to renderer.material should actually create a copy of the material (as opposed to renderer.shared$$anonymous$$aterial), so it's surprising this is the effect.
I actually believe your code is not correct. I would modify your Update to:
private void Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100)) {
if (hit.transform == transform) {
renderer.material = highLight;
return;
}
}
renderer.material = normal;
}
Answer by Igor_Vasiak · Apr 27, 2017 at 06:46 PM
Hover over... If by saying this you mean the mouse, then it's simple: use OnMouseEnter() and OnMouseExit().
void Start ()
{
GetComponent<Renderer>().material = normal;
}
void OnMouseEnter ()
{
GetComponent<Renderer>().material = highLight;
}
void OnMouseExit ()
{
GetComponent<Renderer>().material = normal;
}
This approach worked. I completely forgot about the On$$anonymous$$ouse methods. Thanks.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to translate object using script? 1 Answer