Changing color of of gameObject in Unity

烈酒焚心 提交于 2021-01-29 06:40:23

问题


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.

  1. There's no light (a directional light or a point light) as pointed out by user2320445.

  2. There is a light but you haven't imported the System.Collections namespace, i.e., your program misses the statement using System.Collections; in the beginning of the code. If you want to write the code without using the System.Collections namespace, then you can replace the line

    gameObject.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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!