Hi,
I’d love to check if the current color is assigned.
This whole idea is based on similar custom list of gameobjects where the check does work fine.
I do understand why. as the warning states: Cannot convert null to color because it’s a value type.
Therefor the else check is unreachable.
The code does work, but i am trying to get rid of the warning.
However. I can’t solve it how to check it in a correct fashion.
Color currentColor = new Color();
public List<Color> colorList = new List<Color>();
if (GUILayout.Button ("press me")) {
if (currentColor != null) {
colorList.Add (currentColor);
currentColor = null;
} else {
EditorGUILayout.HelpBox ("Please Enter a color", MessageType.Info);
}
}
Thanks for your insights.
4 Answers
4
Can you not just use Color.clear (as used in the code in your comment). Then use Equals() not == e.g.
if (! currentColor.Equals(Color.clear)) {
_target.colorList.Add (currentColor);
currentColor = Color.clear;
} else {
EditorGUILayout.HelpBox ("Please Enter a valid color", MessageType.Info);
}
Note that
Debug.Log(Color.clear.Equals(new Color()));
…outputs true, so I would guess a EditorGUILayout.ColorField() would default to Color.clear, but that’s a guess.
If someone does choose Color.clear i.e. rgb (0,0,0,0) in the picker then it would still hit your else block, but that’s good, assuming you don’t want a user to choose that as it would not be a valid value. Hence me changing the HelpBox message 
So with your sprite and gameobject checks for null, the empty slot is represented as “null” when you create a new slot but there is no gameobject in it. However, with colors, that new slot is immediately filled with a default color of white or clear.
This means that when you do your check, you can see if the color == white instead of “null”, as a value actually exists there, not nothing. You could change this starting value to another if you want the default value to be a color the user can choose.
See comparing colors here.
I think this should solve your problem for checking for null.
You could simply create your own class, as a wrapper for color, and check it for null there, or you could try use nullable operator Color? a;
Why not use :
On script:
public Color mainColor = default(Color);
On the editor script:
if (mainColor == default(Color) {
// Assignates a color if the current is Null
}
When you Initialize the Color, always assign a default(Color). Thats my flag when y need to do something when the color is Null.
What do you mean by checking the current color?
– HazzangerThanks all for your knowledge and insights. I'll test it out. Thank you very much!
– zero_equals_zero@jacobotrf See this [Question][1] [1]: http://answers.unity3d.com/questions/777838/unity-like-facebook-page-through-app.html
– Sergio7888