Search code examples
bukkit

How to convert a string to a Location Object Bukkit Plugin


I was wondering how I can convert a string (Loaded from the config). Convert into a Location object. I've already tried this code:

private Location StringToLocation(String input, Main plugin) {
    Location world = new Location(Bukkit.getWorld(plugin.getConfig().getString("world")), 0, 0, 0);
    int index;
    int LengteString;
    String[] myCoordinaat = { "", "", "" };


    for (int iLoop = 0; iLoop < 2; iLoop++)
    {
        index = input.indexOf(",");
        LengteString = input.length() - index;
        myCoordinaat[iLoop] = input.substring(index, LengteString);
        input = input.substring(0, index + 1);
    }
    myCoordinaat[2]=input;

    Bukkit.getLogger().info("x: " + myCoordinaat[0] + " y:" + myCoordinaat[1] + " z:" + myCoordinaat[2]);

    world.setX(Double.parseDouble(myCoordinaat[0]));
    world.setY(Double.parseDouble(myCoordinaat[1]));
    world.setZ(Double.parseDouble(myCoordinaat[2]));
    return world;
}

Thanks in advance!


Solution

  • There is a very easy solution to your problem that doesn't even involve you parsing the location yourself.

    //Save location
    getConfig().set("path.to.location", loc);
    saveConfig();
    
    //Load location
    Location location = (Location) getConfig().get("path.to.location");
    

    You can basically store the object in the config and then restore it. Just keep in mind that the world needs to be loaded for the Location to be parsed.