- Home /
How to change object material with GetComponent in Unity 5?
Hi everyone.
Does anyone know how I can change this GetComponent script, so that on MouseOver it changes the material instead of the material.color? The error is causing my game build to crash, so any help would be great! Thanks :)
using UnityEngine; using System.Collections;
public class ChangeColor : MonoBehaviour {
private Color initialColor;
void Start () {
initialColor = GetComponent<Renderer> ().material.color;
}
void OnMouseOver () {
GetComponent<Renderer> ().material.color = Color.red;
}
void OnMouseExit() {
GetComponent<Renderer> ().material.color = initialColor;
} }
someone already answered your question, but your code shouldnt be causing a crash. $$anonymous$$ost likely you are trying to do something on a UI element, and UI elements do not have a Renderer. They have a canvas renderer, which does not derive from renderer. You probably just need to change the "GetComponent()" to "GetComponent()" and then change the material color.
Answer by reddead12 · Dec 06, 2015 at 04:34 PM
using UnityEngine;
using System.Collections;
public class SomeCode : MonoBehaviour
{
public GameObject GameOBJ;
public material Mat;
void Start()
{
GameOBJ.GetComponent<Renderer>().material = Mat;
}
}
This gave me no error so if you can assign both variables in some way it should be fine.