Convert string variable into floats?

print(restoreplayerpos);
// variable contains -7.4, 1.4, 6.5

// restore player position
var playerObject = GameObject.Find("player");
playerObject.transform.position = Vector3(restoreplayerpos); // need to convert the variable restoreplayerpos into a float somehow?

2 Answers

2

You can use string.Split() for splitting the string values and float.Parse() for string to float conversion.

float.Parse() works even if the input string contains whitespaces. So " 1.4" will be converted without any errors.

Try this:

Javascript

var sStrings = restoreplayerpos.Split(","[0]);

var x : float = float.Parse(sStrings[0]);
var y : float = float.Parse(sStrings[1]);
var z : float = float.Parse(sStrings[2]);

var playerObject = gameObject.Find("player");
playerObject.transform.position = new Vector3(x, y, z);

C#

var sStrings = restoreplayerpos.Split(","[0]);

float x = float.Parse(sStrings[0]);
float y = float.Parse(sStrings[1]);
float z = float.Parse(sStrings[2]);

var playerObject = GameObject.Find("player");
playerObject.transform.position = new Vector3(x, y, z);

your answer is much cleaner then mine ^^ I totally forgot about Split.

–

Thank you both. I'll try this when I'm able to this evening and see how it goes. Much appreciated as always.

–

Your answer would get closer to perfect with a try/catch section.

–

Thank you keburanuil. That has worked brilliantly. Thanks to everyone else too, have chosen keburanuil's answer as it seemed the most efficient.

–

string TheString = { “-7.4”, “1.4”, “6.5” };
float VectorPosition = new float[TheString.Length];
Vector3 restoreplayerpos = new Vector3();

                  for (int i = 0; i < TheString.Length;i++ )
                  {
        
                     VectorPosition _= float.Parse(TheString*);*_

restoreplayerpos.x = VectorPosition[0];
restoreplayerpos.y = VectorPosition[1];
restoreplayerpos.z = VectorPosition[2];
}

var playerObject = GameObject.Find(“player”);

playerObject.transform.position = new Vector3( restoreplayerpos.x, restoreplayerpos.y,restoreplayerpos.z);
why do you need it to be a string ??
I didn’t test it but It should work.