- Home /
Parsing a String to a Color
How come this works:
var idk1 : String = "123";
var idk2 : int = int.Parse(idk1);
print(idk2);
But this doesn't:
var idk1 : String = "(1.0, 1.0, 1.0, 1.0)";
var idk2 : Color = Color.Parse(idk1);
print(idk2);
I get this error: MissingMethodException: Method not found: 'UnityEngine.Color.Parse'.
Answer by Peter G · Aug 10, 2011 at 04:02 AM
Because there isn't a Color.Parse() method. You can't just make up methods. You need to check the API to see if they exist. int.Parse() is a real method in the .Net library. It wouldn't be very hard to write a parser for a string though:
public static class ColorExtensions {
public static function ParseColor (col : String) : Color {
//Takes strings formatted with numbers and no spaces before or after the commas:
// "1.0,1.0,.35,1.0"
var strings = col.Split(","[0] );
var output : Color;
for (var i = 0; i < 4; i++) {
output[i] = System.Single.Parse(strings[i]);
}
return output;
}
}
That should work. It will give you a warning saying that declaring a static function in a static class is redundant, but I prefer to leave it in for clarities sake. It isn't a harmful warning.
Example:
var col = ColorExtensions.ParseColor( "0.0,1.0,.75,.2" );
Debug.Log(col);
Quick question, can you or someone else give me a link to the api your using for these functions? Because I can't find it on here:
@UnityGuy1243: Unity doesn't use WPF. http://msdn.microsoft.com/en-us/library/ms229335(v=VS.90).aspx
I suggest to use this ins$$anonymous$$d:
var output = Color.white;
var count = $$anonymous$$athf.$$anonymous$$in(strings.Length, 4);
for (var i = 0; i < count; i++) {
This allows you to omit the alpha value and avoids errors if you pass to many values.
Newbie here...
Where do you place this script? I tried simply creating a new C# script in Unity, and cutting/pasting your code... I got a ton of red squiggles.
Well, it doesn't really matter where you put it, but this is not C# code. This is UnityScript (Unity's javascript dialect). So you would need to create a "Javascript" script. However if you use C# (and i would recommend that) you want to translate it into C# ^^.
// C#
public static class ColorExtensions
{
public static Color ParseColor(string aCol)
{
var strings = aCol.Split(',');
Color output = Color.black;
for (var i = 0; i < strings.Length; i++)
{
output[i] = float.Parse(strings[i]);
}
return output;
}
}
Your answer
Follow this Question
Related Questions
How to convert a string to an int? 1 Answer
int to char conversion in JS ? 2 Answers
Type 'int' does not support slicing 1 Answer
Part of string not showing 1 Answer
How to reference a variable in another script based on string in c# 0 Answers