I want to change an object’s transparency by pressing the key “g” at run-time. The following is my code in Update():
if(Input.GetKeyDown(KeyCode.G)){
gameObject.GetComponent ().material.color.a = 0.5f;
}
But there is an error for my code saying I cannot change the value of returning value. Do you guys have any idea how to change transparency at run-time?
You can’t change color property directly because Color is a structure and not a class. You’re trying to change a temporary copy of the color property and not the property itself. Just google the difference between class and struct in C#. And here is what you have to do.
Color c = gameObject.GetComponent<Renderer>().material.color;
c.a = 0.5f;
gameObject.GetComponent<Renderer>().material.color = c;
Note that this isn’t very efficient way how to do it. You should cache the material reference in Start or Awake to avoid calling GetComponent<> repeatedly .
Thanks. I tried your method. But it does not produce the expected result. The Unity just produces a new material instance. Nothing changes in my scene.
Yes, Renderer.material creates new material instance for this renderer only. I guess you want to use Renderer.sharedMaterial instead? Also the shader that your material is using has to support transparency. Not all of them do.
Also if the object is using an opaque shader changing the alpha value won’t do anything. You’ll also have to change the shader in use (or if you’re using the standard shader do a bunch of other stuff).