I’ve been looking for a way to convert a string (which was created by a vector3) to a vector3 back again. I could not find anything useful yet.. How can I make this?
Thanks
2 Answers
2Did you look at String methods?
Use those in a function:
public static Vector3 StringToVector3(string sVector)
{
// Remove the parentheses
if (sVector.StartsWith ("(") && sVector.EndsWith (")")) {
sVector = sVector.Substring(1, sVector.Length-2);
}
// split the items
string[] sArray = sVector.Split(',');
// store as a Vector3
Vector3 result = new Vector3(
float.Parse(sArray[0]),
float.Parse(sArray[1]),
float.Parse(sArray[2]));
return result;
}
any clue why it says that the input string is not in a correct format? here’s the code i tested this with:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestConversion : MonoBehaviour
{
string s = "(0.0,0.0,0.0)";
public static Vector3 StringToVector3(string sVector)
{
// Remove the parentheses
if (sVector.StartsWith ("(") && sVector.EndsWith (")")) {
sVector = sVector.Substring(1, sVector.Length-2);
}
// split the items
string[] sArray = sVector.Split(',');
// store as a Vector3
Vector3 result = new Vector3(
float.Parse(sArray[0]),
float.Parse(sArray[1]),
float.Parse(sArray[2]));
return result;
}
// Update is called once per frame
void Update()
{
Debug.Log(StringToVector3(s));
}
}
I think the problem is when this line runs: sVector = sVector.Substring(1, sVector.Length-2); in order to separate the floats, it's looking for the way a vector is normally written with spaces. So try: string s = "(0.0, 0.0, 0.0)"; and see if that works or it might be also that it cannot convert to float: string s = "(0.0f, 0.0f, 0.0f)";
– wideeyenow_unity
Thank you for your help. You are a lifesaver
– Nirvana4Thank you very much :) Helps a lot
– kmithun9