Hey, all. I’m trying to run this piece of code but I can not figure out what’s going on. I’ve been at it for about 4 hours and nothing on Google seems to help much. I keep getting an error that reads “Assets/Plane.cs(6,23): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `UnityEngine.Component.renderer”
public class Plane : MonoBehaviour {
Color color = renderer.material.color;
void Start () {
color.r = 0.0f;
color.g = 0.0f;
color.b = 0.0f;
if(Application.loadedLevel == 1)
{
color.r = PlayerPrefs.GetFloat("planeColorR");
color.g = PlayerPrefs.GetFloat("planeColorG");
color.b = PlayerPrefs.GetFloat("planeColorB");
}
renderer.material.color = color;
}
I have modified this code a lot so this is definitely not a first attempt.
You need to move the initialization into Start(). So you declare:
Color color;
Then in Start():
color = renderer.material.color;
you need this:
renderer.material.SetColor (“_Color”, color);
dot syntax does not work with materials.
also note "_Color"
is the address of the _Color
variable in a shader, if your material’s shader uses another variable you’ll need to find out what it wants.
[edit (big edit ;)]
just noted you CAN use dot syntax (thanks tanoshimi), although this presumes that the _Color
variable exists at all. several shaders do not have the _Color variable, and if you're using a custom shader, they could easily for instance call it
_Tintor
_Colour`, etc.
However I also note you’re defining the variable at the beginning as
Color color = renderer.material.color;
I’m pretty sure that you can’t initialise a variable with a get texture like this before any events.
Try changing it to this.
Color color;
and setting the color in a start routine instead.
void Start(){
color=renderer.material.GetColor("_Color");
}