Home > Net >  Use an if statement to make the player teleport
Use an if statement to make the player teleport

Time:03-27

What is the best way to call Vector3 result from if (s == result) in order to teleport the player? This is the C# code I'm using now:

public Vector3 result;

public void ReadStringInput(string s)
{
    input = s;
    if (s == result)   //Read input string from InputField here.
    {   
        GameObject.Find("FirstPersonPlayer").transform.position = transform.position   result;
    }
}

public Vector3 StringToVector3(string s)
 {
     // Remove the parentheses
     if (s.StartsWith ("(") && s.EndsWith (")")) {
         s = s.Substring(1, s.Length-2);
     }
 
     // split the items
     string[] sArray = s.Split(',');
 
     // store as a Vector3
     Vector3 result = new Vector3(
         float.Parse(sArray[0]),
         float.Parse(sArray[1]),
         float.Parse(sArray[2]));

     return result;
 }

CodePudding user response:

First of all you might want to handle bad user input and the possible exceptions thrown by it better and do e.g.

private readonly char[] removeCharcters = new char[] { '(', ')' };

private bool StringToVector3(string s, out Vector3 result)
{
    result = default;

    if(s == null)
    {
        // Input is invalid
        return false;
    }

    // split the items
    var parts = s.Split(',');

    if(parts.Length != 3)
    {
        // Input invalid
        return false;
    }

    for(var i = 0; i < 3; i  )
    {
        // clean the split part
        // first remove any leading or trailing whitespace in general
        // then also remove the ( and )
        var part = parts[i].Trim().Trim(removeCharcters);

        
        if(!float.TryParse(part, out var value))
        {
            // not a valid float -> Input invalid
            return false;
        }

        result[i] = value;
    }

    // Valid Vector3
    return true;
}

And then I think what you wanted to do would be e.g.

// already reference this via the Inspector if possible
[SerializeField] private Transform _firstPersonPlayer;

public void ReadStringInput(string input)
{
    if(!StringToVector3(input, out var position))
    {
        Debug.LogWarning($"\"{input}\" is not a valid {nameof(Vector3)}!");
        return;
    }  

    // only get when needed - Find is expensive
    if(!_firstPersonPlayer) _firstPersonPlayer = GameObject.Find("FirstPersonPlayer").transform;

    _firstPersonPlayer.position = position;
}
  • Related