问题
Okay so I have this code.
void Start () {
gameObject.GetComponent<Renderer> ().material.color = Color.green;
}
I expected my gameObject to change its color to green. I imported it as black and in the inspector it has turned to green however in the actual application it does not appear as green. I cant use gameObject.renderer.material.color = Color.green
since unity tell me its basically outdated and that I have to use the new version. This is going to be really simple but what am I missing? Thanks in advance.
UPDATE: When I run the code a tab pops up in the inspector 'Sprites-Default (instance)' and if I change the selection box to Unlit > Color it works. Is there anyway of making this stick?
回答1:
the color changes but you cant see the result because the shader in your material needs light and you don't have lights so you will always see it black so you can add a light source or change the materials shader to unlight.
回答2:
If you are trying to change a 2D sprite color try GetComponent<SpriteRenderer>().color = Color.green instead of just get "Renderer" component or try to setColor() with specular shader instead of direct attribution (you'll need a light source in scene).
回答3:
There are always two possibilities of not seeing the result of this code.
There's no light (a directional light or a point light) as pointed out by user2320445.
There is a light but you haven't imported the
System.Collections
namespace, i.e., your program misses the statementusing System.Collections;
in the beginning of the code. If you want to write the code without using theSystem.Collections
namespace, then you can replace the linegameObject.GetComponent<Renderer> ().material.color = Color.green;
with
gameObject.renderer.material.color = Color.green;
This does not require you to import the System.Collections namespace.
来源:https://stackoverflow.com/questions/31593008/changing-color-of-of-gameobject-in-unity