将两个 Unity 项目导入 Android Studio 无法按预期工作

2023-12-09

我目前正在接受培训,制作使用 Unity 添加一些功能(AR、VR 等)的应用程序。目前我一直在使用 Android Studio 开发 Android,一旦完成,我将在 iOS 上进行训练。

我的目标很简单:我的MainActivity显示两个按钮,每个按钮调用一个单独的 Unity 项目(从 Unity 导出为 Google Android 项目)来启动其场景。

为此,我导入了这两个 Unity 项目Scene1 and Scene2作为库,我通过启动它们的活动来调用它们(参见下面的代码)。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void goToUnity1(View v){
        Intent intent = new Intent(this, com.example.unityscene1.UnityPlayerActivity.class);
        startActivity(intent);
    }

    public void goToUnity2(View v){
            Intent intent = new Intent(this, com.example.unityscene2.UnityPlayerActivity.class);         
            startActivity(intent);

     }
}

及其 AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multipleunity">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="com.example.unityscene1.UnityPlayerActivity"></activity>
    <activity android:name="com.example.unityscene2.UnityPlayerActivity"></activity>


</application>

The UnityPlayerActivity文件在Scene1 and Scene2由 Unity 生成,因此它们很相似(这是它们的onCreate方法):

public class UnityPlayerActivity extends Activity {
    protected UnityPlayer mUnityPlayer; // don't change the name of this variable; referenced from native code


    // Setup activity layout
    @Override protected void onCreate (Bundle savedInstanceState)
    {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        getWindow().setFormat(PixelFormat.RGBX_8888); // <--- This makes xperia play happy

        mUnityPlayer = new UnityPlayer(this);
        setContentView(mUnityPlayer);
        mUnityPlayer.requestFocus();
    }

    ...
}

代码编译没有任何问题,应用程序启动并显示 MainActivity 及其两个按钮。当我单击第一个按钮时,它会按我的预期启动第一个 Unity 场景。然而,当我单击第二个按钮时,它也会启动第一个 Unity 场景而不是第二个。

所以我试图理解为什么会发生这种情况,到目前为止我可以说的是:

  • 我没有错误地放置两次相同的 Unity 项目
  • 改造前Scene2进入图书馆它本身就可以很好地工作
  • 活动com.example.unityscene2.UnityPlayerActivity当我单击第二个按钮时调用

UPDATE

在花了几个小时之后,我确信问题来自于我在 Google Android 项目中导出时 Unity 提供的资源名称,这些资源名称始终相同(unity-classes.jar).

这是我读到的here:

Android 开发工具将库项目的资源与应用程序项目的资源合并。如果资源的 ID 被多次定义,工具会从应用程序或具有最高优先级的库中选择资源,并丢弃其他资源。

除此之外,如果我有多个库,则优先级与依赖项顺序(它们在 Gradle 依赖项块中出现的顺序)相匹配。

因此,我尝试颠倒依赖项的顺序,将第二个 Unity 项目放在第一个项目之前,正如预期的那样,两个按钮都会启动 Unity 的第二个场景。

现在我知道了,有没有办法避免这种名称冲突?


我没有解决我的问题,但我设法找到一种方法来避免它:我决定制作一个更大的项目,其中包括两个不同的场景(一个使用 Vuforia AR,另一个使用一些 UI 文本),而不是导入两个小型 Unity 项目。接下来的挑战是找到一种方法,当我单击我在 Android 上设计的关联按钮时,调用正确的 Unity 场景。

Unity

在每个场景中我创建了一个空对象(我称之为SceneManagerObject)将附加脚本GoToScene。在此脚本中将有以下方法:

private void ChangeScene(string sceneName)
{
    SceneManager.LoadScene (sceneName);
}

public void ReceiveJavaMessage(string message)
{
    if (message.Equals ("Scene1") || message.Equals ("Scene2")) 
    {
        ChangeScene (message);
    } 
    else 
    {
        Debug.Log ("The scene name is incorrect");
    }
}

第二种方法将是从 Java 代码中调用的方法。

然后我在每个场景上创建了一个 UI 按钮,它将调用onClick单击方法时,其目的是能够返回到 Android 而不破坏 Unity 活动,以便我们可以在需要时恢复它。为此,我使用脚本创建了另一个空对象GoBackToAndroid随附的:

public class GoBackToAndroid : MonoBehaviour {
public string activityName; // contains the name of the activity I want to go when I quit this scene

public void onClick()
{
    callJavaMethod();
}


private void callJavaMethod()
{
    AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer);
    AnroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
    jo.Call("ReceiveUnityMessage", activityName); // Will call a method in Java with activityName as parameter
}

在我将项目导出为 Google Android 项目并为下一步做好准备之后,Unity 就这样了。

安卓工作室

将 Unity 项目作为库导入后。我创建了三个活动:MainActivity, SecondActivity and MultipleScenesUnityActivity:

public class MultipleScenesUnityActivity extends UnityPlayerActivity {
    public static boolean unityIsRunning = false; // true if a Unity Activity is running on background


    @Override protected void onDestroy()
    {
        unityIsRunning = false;
        super.mUnityPlayer.quit();
        super.onDestroy();
    }

    @Override protected void onResume()
    {
        Intent currentIntent = getIntent();
         // If there's no Unity Activity inside the back stack
        // (meaning it just had been created)
        if (!unityIsRunning)
        {
             super.mUnityPlayer.UnitySendMessage("SceneManagerObject", "ReceiveJavaMessage", currentIntent.getStringExtra("sceneName");
        }
        unityIsRunning = true;
        super.onResume();
        super.mUnityPlayer.resume();
    }

    public void ReceiveUnityMessage (String messageFromUnity)
    {
        Intent intent;
        if (messageFromUnity.equals("MainActivity"))
        {
            intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
        else if (messageFromUnity.equals("SecondActivity"))
        {
            intent = new Intent(this, SecondActivity.class);
            startActivity(intent);
        }
        else 
            Log.d("Test", "The activity " + messageFromUnity + " doesn't exist");
    }
}

The ReceiveUnityMessage是我们离开 Unity Activity 时调用的方法,其目的是引导我们前往我们想去的 Activity。

然后MainActivity (the SecondActivity遵循相同的模式):

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void goToActivity2(View view) // called when I click on a button
    {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }

    public void goToUnity(View view) // called when I click on another button
    { 
        Intent intentUnity = new Intent(this, MultipleScenesUnityActivity.class);

        if (unityIsRunning)
        {
            intentUnity.removeExtra("sceneName"); // We have to clean the extra before putting another one otherwise we'll get always the same Unity scene

            /*  If set in an Intent passed to Context.startActivity(), this flag will cause the launched activity to be brought
             *  to the front of its task's history stack if it is already running. */
            intentUnity.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

            /* We send a string to Unity which, when received, will change the scene.
            * This ONLY works when the Unity activity is running on background. */
            UnitySendMessage("SceneManagerObject", "ReceiveJavaMessage", "Scene1");
        }

        else
        {
            /* The intent gets a key with its String value. The value has to be the name of the Unity
            * scene and is received in UnityActivity1 when the activity starts.*/
            intentUnity.putExtra("sceneName", "Scene1");
        }
        startActivity(intentUnity);
    }
}

因此,我所做的就是通过发送消息来连接所有内容,以便我可以管理我想要启动的场景,活动也是如此。

我确信有更好的方法可以做到这一点,我仍然是一个新手,我可能会很笨拙。无论如何,我设法避免了我原来的问题,所以如果有人面临同样的问题,这个答案可能是一个有趣的选择。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将两个 Unity 项目导入 Android Studio 无法按预期工作 的相关文章

随机推荐

  • 预计读取 4 个标头字节,但只收到 0

    我编写了一个 Windows 服务 它使用 SSH 安全外壳 将数据从 CSV 文件复制到 PhpMyAdmin 在线数据库 连接打开时触发错误 MySql Data MySqlClient MySqlProtocolException H
  • 非常简单的程序的未定义引用

    当我安装 Ubuntu 11 10 后 出现奇怪的错误 我想在我的 C 程序中使用 GD 因此我安装了软件包 libgd2 xpm dev 一切都已安装 文件 gd h 和 libgd a 位于 usr include 和 usr lib
  • Spark:PySpark + Cassandra 查询性能

    我已在本地计算机 8 核 16GB 内存 上设置 Spark 2 0 和 Cassandra 3 0 以进行测试并进行编辑spark defaults conf如下 spark python worker memory 1g spark e
  • str.strip() 奇怪的行为[重复]

    这个问题在这里已经有答案了 gt gt gt t1 abcd org gz gt gt gt t1 abcd org gz gt gt gt t1 strip g abcd org gz gt gt gt t1 strip gz abcd
  • 通过与另一个数组进行比较来查找数组中的元素

    我有一个矩阵 a 1 cancer 2 cancer 3 cancer 4 noncancer 5 noncancer 我有另一个带有值的矩阵 b 4 5 2 现在我必须将 b 矩阵值与 a 值进行比较 输出应该是 output 4 non
  • 如何有效生成对称矩阵的下三角索引

    我需要生成下三角矩阵索引 行和列对 当前的实现效率低下 内存方面 特别是当对称矩阵变大 超过 50K 行 时 有没有更好的办法 rows lt 2e 01 id lt which lower tri matrix rows rows TRU
  • Android中Handler-Looper的实现

    我有处理程序的活动 UI 线程 我启动新线程并创建 handler post new MyRunnable 新工作线程 Android 文档谈到 post 方法 导致 Runnable r 添加到消息队列中 runnable 将在该处理程序
  • Selenium webdriver (c#) - 基于属性查找按钮

    我正在尝试根据属性获取下面按钮的句柄gl command 我知道我可以使用Cssselector通过定位器 但在这种情况下我不想这样做 我应该指出 这只是 AUT 中的众多按钮之一
  • group_by 总结 group_by dplyr 之外的内容

    我正在尝试将此数据集中的 id 与日期分组 但我想根据组外的功能之一进行总结 library dplyr library lubridate set seed 100 df lt data frame ids sample c 436247
  • 如何从 ASP.NET MVC 中的 HttpModule 执行控制器操作?

    我有以下内容IHttpModule我试图找出如何从控制器对给定的绝对或相对 URL 执行操作 public class CustomErrorHandlingModule IHttpModule region Implementation
  • 使用 mySQL 进行 GROUP_CONCAT 后的数据求和

    我正在使用 phpMyAdmn 并且在 mySQL 中有这个查询 SELECT BIL Date BIL Rate BIL Quantity GROUP CONCAT COALESCE STX Amount 0 AS ApplicableT
  • 需要工作表脚本将图像保存到驱动器

    我需要一个与 google 工作表一起使用的脚本 以将 img url 列表保存到特定的 google 驱动器文件夹 并使用来自另一个单元格的文件命名 例如 A 列 文件 URL 图像文件路径 jpgB 列 另存为名称 image 1 自动
  • Javascript-按值删除数组项[重复]

    这个问题在这里已经有答案了 我的情况 var id tag 1 2 3 78 5 6 7 8 47 34 90 我想delete where id tag 90并返回 var id tag 1 2 3 78 5 6 7 8 47 34 我怎
  • 数据框中连续出现的情况

    我有上面的数据框包含不同的测量值 我想确定连续测量值 长度大小大于或等于 6 w一次拍摄t 例如 在以下情况id 1 from t3 t8有6连续的w记录的措施 我想将结果保存到2个数据框中 df1 At least 6 consecuti
  • iOS NSDateFormatter 需要 NSLocale 即使它是 UTC

    我怀疑我无法理解为什么会这样 我向这个网站的诸神求助 我有一个约会是这样的 1982 01 01T00 00 00Z 当我显示服务器发送的任何内容时 我知道 客户要求 不是好的做法 我强制设备使用以下方法具有该时区 在没有错误检查的情况下进
  • 很困惑将代码放入 AsyncTask 中

    我有这个代码来接收聊天消息 但当我试图把它放进去时我很困惑AsyncTask 我有警告read cannot be resolved for read readline 当我把它放进去时postexecute 我想让这段代码在后台工作 以检
  • 不可能将对象添加到可变数组

    我正在尝试将 Song 对象添加到可变数组中 但我很困惑 因为尽管添加了对象 但数组的计数并未增加 Song h import
  • Python 中的 cURL 帮助

    我必须向服务器发送请求 在该网站的 API 文档中有一个在 PHP 中使用 cURL 的示例 ch curl init curl setopt ch CURLOPT URL http api website com curl setopt
  • 在 HTML 中呈现任意 JSON

    我正在编写一个数据查看器页面来呈现从服务器作为 JSON 发送的对象 JSON 对象的内容和复杂性各不相同 从具有少量属性的平面对象到具有多层嵌套和数组字段的较大结构 我想做的是渲染对象的简单表示 可能作为 ul 从那里我可以添加一些东西来
  • 将两个 Unity 项目导入 Android Studio 无法按预期工作

    我目前正在接受培训 制作使用 Unity 添加一些功能 AR VR 等 的应用程序 目前我一直在使用 Android Studio 开发 Android 一旦完成 我将在 iOS 上进行训练 我的目标很简单 我的MainActivity显示