首页 > 解决方案 > Elixir - 获取 args 中的值,从 Unity 传递

问题描述

我的任务是为 Unity 游戏创建服务器(使用 Elixir 和 Merigo SDE)。

现在,我满足于从 Unity (C#) 发送数据,我这样做如下:

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);
    }
}

在merigo方面,我有这个:

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

现在,除了 Unity 的一些错误,Elixir 方面确实可以工作;它显示以下内容:

测试动作触发... %{"direction_x" => 0.9692893624305725, "direction_y" => 0.0, "power" => 12.293679237365723}

但我不知道如何从 args 中获取这些值并将它们返回。args.power没用。

还有什么我可以尝试的吗?

标签: c#unity3delixir

解决方案


您的地图将其键作为字符串,即二进制文件。当且仅键是原子时,点表示法适用于映射。

你有两个选择。

要么通过Access

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

或者,或者,直接在函数子句中对其进行模式匹配

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

或者,解构它:

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

旁注:按照惯例,中的函数以下划线表示法命名(do_request而不是doRequest,),当映射键是原子时,我们使用带有冒号的较短表示法:(​​而不是%{:results => "success"}do %{results: "success"}。)


推荐阅读