【问题标题】:How to share memory in unity running on android?如何在android上统一共享内存?
【发布时间】:2019-09-02 14:57:57
【问题描述】:

我为一个设备编写了一个 USB 驱动程序,它每秒更新 x、y、z 位置 200 次,我不想调用某些函数来每秒 200 次获取新值,从而更新共享上的值内存位置。 是否可以将 IntPtr 传递给 AndroidJavaObject.call 方法并使用它来访问共享内存或其他方式? 还是有不同的方法来解决这个问题? 发布我的代码没有意义,因为没有关于共享内存的内容。

在统一 C# 方面:

        AndroidJavaClass unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
        AndroidJavaObject unityContext = unityActivity.Call<AndroidJavaObject>("getApplicationContext");


        float[] res = new float[7];
        IntPtr ptr = Marshal.AllocHGlobal(res.Length * sizeof(float));

        var ajc = new AndroidJavaObject("com.example.t265lib.USBController", unityContext, 256, ptr, null);

在 Java 方面,它只是一个构造函数:

    public USBController(Context context, int chunkSize, int ptr,TextView deb) {
        if (deb != null) debugging = deb;
        if (chunkSize != 0) CHUNK_SIZE = chunkSize;
        msg = new byte[9];
        msgResponse = new byte[8];
        resPtr = new float[7];
        this.context = context;
        usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
    }

【问题讨论】:

标签: java c# unity3d


【解决方案1】:

您可以将您在 Android-Plugin 中的位置保存到一个变量中。然后根据需要从 Unity 轮询它(例如在更新循环中)。

安卓

// inner class for position values
public class PositionData {
    public int x;
    public int y;
    public int z;
}

// access data from unity
public PositionData getCurrentPosition() { 
    // TODO: make thread-safe
    return mCurrentPosition;
}

团结

// class for position values
public class PositionData
{
    public int X;
    public int Y;
    public int Z;
}

// poll position from Android (usbController is initialised somewhere else)
public PositionData ReadPositionData()
{
    var data = usbController.Call<AndroidJavaObject>("getCurrentPosition");

    if (data == null)
    {
        Debug.LogError("Could not retrieve data from Android.");
        return null;
    }

    var positionData = new PositionData
    {
        X = data.Get<int>("x"),
        Y = data.Get<int>("y"),
        Z = data.Get<int>("z")
    };

    return positionData;
}

USB-Communication 应该在自己的线程中,并且对其值的访问必须是线程安全的(Unity 在主线程上运行)。

您还可以在 Android 中实现一些过滤来平滑您的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-12
    • 2011-11-21
    • 2018-02-15
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    相关资源
    最近更新 更多