Split string into three pieces?
I am working on sending multiplayer packets, and I am sending each player a message containing : "x[PLAYER POSITION X]y[PLAYER POSITION Y]z[PLAYER POSITION Z]". (Replace the brackets with the actual positions)
I want to make a vector from this information, but I am not skilled at working with string functions.
How would I put this info into a Vector3?
(C# ONLY PLEASE)
Thank you, Bryce
Comment
Best Answer
Answer by ARKMs · Nov 05, 2015 at 08:29 AM
I have this code maybe help you:
void Start()
{
//packed
float[] pos = {transform.position.x, transform.position.y, transform.position.z};
string posINstring = Joinsfloats(pos);
print(posINstring);
//read packed
float[] newpos = Split_floats(posINstring);
transform.position = new Vector3(newpos[0], newpos[1], newpos[2]);
print(transform.position);
}
public string Joinsfloats(float[] ar)
{
return System.String.Join("_", new List<float>(ar).ConvertAll(i => i.ToString()).ToArray());
}
public float[] Split_floats(string tx)
{
List<float> lista = new List<float>();
int lasti = 0;
while (lasti < tx.Length)
{
int index = tx.IndexOf('_', lasti);
if (index != -1)
{
float num = float.Parse(tx.Substring(lasti, index - lasti));
lista.Add(num);
lasti = index + 1;
}
else
{
float num = float.Parse(tx.Substring(lasti, tx.Length - lasti));
lista.Add(num);
lasti = tx.Length;
}
}
return lista.ToArray();
}
No. It won't work for my situation. Thank you, but I need to split the string.
In my function 'Split_floats()', split a string like this "50_10_30" in 3 floats, in you case, you can adapt it for split with '[' and ']'.