1
votes

I'm tasked with creating a server (which uses Elixir and Merigo SDE) for a Unity game.

For now, I'm content with sending data from Unity (C#), which I do as follows:

public class ShotController : MonoBehaviour
{
    public ConnectionHandler conHandler;
    public void Shoot(Vector3 direction, float power) {
        DataToSend data = new DataToSend();
        data.power = power;
        data.direction_x = direction.x;
        data.direction_y = direction.y;
        conHandler.SendShotDetails(data);
    }
}

public class DataToSend
{
    public float power = 0;
    public float direction_x = 0;
    public float direction_y = 0;
}

public class ConnectionHandler : MonoBehaviour, Playground.App.IPlaygroundDelegate
{
    public void SendShotDetails<T>(T data) where T : class
    {
        Debug.Log("Shot!");
        Playground.App.Manager.LocalGame.ScriptRequest("test_action", data);
    }
}

On the merigo's side, I have this:

# Test receive request
def doRequest("test_action", args) do
    # Read the player data
    Sys.Log.debug("Test action fired... #{inspect args}")
    %{:results => "success"}
end

Now, save for some errors with Unity, the Elixir side does work; it displays the following:

Test action fired... %{"direction_x" => 0.9692893624305725, "direction_y" => 0.0, "power" => 12.293679237365723}

But I have no idea how to get those values from args and return them back. args.power didn't work.

Is there something else I can try?

1

1 Answers

1
votes

Your map has its keys as strings aka binaries. Dot notation works for maps if and only keys are atoms.

You have two options.

Either get to the value through Access

map =
  %{"direction_x" => 0.9692893624305725,
    "direction_y" => 0.0,
    "power" => 12.293679237365723
  }
map["power"]
#⇒ 12.293679237365723

Or, alternatively, pattern-match it directly in the function clause

def do_request("test_action", %{"power" => power}) do
  Sys.Log.debug("power is #{power}")
end

or, destructure it:

def do_request("test_action", args) do
  %{"power" => power} = args
  Sys.Log.debug("power is #{power}")
end

Sidenotes: by convention, functions in are named in underscore notation (do_request instead of doRequest,) and when the map keys are atoms, we use shorter notation with a colon : (instead of %{:results => "success"} do %{results: "success"}.)