当前位置: 首页 > news >正文

android集成unity后动态导入 assetsBundle

1、Unity 中创建空物体 BundleLoader 并挂载脚本

using System.Collections;
using System.Diagnostics;
using System.IO;
using UnityEngine;
using static System.Net.Mime.MediaTypeNames;public class LoadSphereBundle : MonoBehaviour
{void Start(){StartCoroutine(LoadSphere());// 测试 Android 或 Editor//#if UNITY_EDITOR//            string path = UnityEngine.Application.dataPath + "/AssetBundles/Android/spherebundle";//#else//        string path = UnityEngine.Application.persistentDataPath + "/spherebundle"; // Android 可读路径//#endif//        LoadSphereByPathBridge(path);}public IEnumerator LoadSphere(){// 正确的路径构建方式#if UNITY_EDITOR// 编辑器模式下的路径string path = UnityEngine.Application.dataPath + "/AssetBundles/Android/spherebundle";#else// 运行时模式下的路径(打包后)string path = UnityEngine.Application.streamingAssetsPath + "/spherebundle";#endifUnityEngine.Debug.Log("尝试从路径加载: " + path);// 加载 AssetBundleAssetBundle bundle = AssetBundle.LoadFromFile(path);if (bundle == null){UnityEngine.Debug.LogError("Failed to load spherebundle from: " + path);UnityEngine.Debug.Log("请确认文件是否存在且路径正确");yield break;}// 加载 prefabGameObject spherePrefab = bundle.LoadAsset<GameObject>("sphere");if (spherePrefab != null){Instantiate(spherePrefab, Vector3.zero, Quaternion.identity);UnityEngine.Debug.Log("成功加载并实例化 sphere prefab!");}else{UnityEngine.Debug.LogError("Failed to load prefab 'sphere' from bundle!");// 调试:列出bundle中所有资源UnityEngine.Debug.Log("Bundle中包含的资源:");foreach (string name in bundle.GetAllAssetNames()){UnityEngine.Debug.Log("- " + name);}}bundle.Unload(false);}// UnitySendMessage 调用入口public void LoadSphereByPathBridge(string path){UnityEngine.Debug.Log("LoadSphereByPathBridge,收到 UnitySendMessage 调用, 路径 = " + path);StartCoroutine(LoadSphereByPath(path));}public IEnumerator LoadSphereByPath(string path){UnityEngine.Debug.Log("尝试从路径加载: " + path);// 加载 AssetBundleAssetBundle bundle = AssetBundle.LoadFromFile(path);if (bundle == null){UnityEngine.Debug.LogError("Failed to load spherebundle from: " + path);UnityEngine.Debug.Log("请确认文件是否存在且路径正确");yield break;}// 加载 prefabGameObject spherePrefab = bundle.LoadAsset<GameObject>("sphere");if (spherePrefab != null){Instantiate(spherePrefab, Vector3.zero, Quaternion.identity);UnityEngine.Debug.Log("成功加载并实例化 sphere prefab!");}else{UnityEngine.Debug.LogError("Failed to load prefab 'sphere' from bundle!");// 调试:列出bundle中所有资源UnityEngine.Debug.Log("Bundle中包含的资源:");foreach (string name in bundle.GetAllAssetNames()){UnityEngine.Debug.Log("- " + name);}}bundle.Unload(false);}
}

2、android 中 使用 UnitySendMessage 调用 LoadSphereByPathBridge方法 加载 ab

(注意 assetsBundle 全部文件拷贝到 /storage/emulated/0/Android/data/com.example.dockwithtuanjie/files/ 目录下 )

package com.example.dockwithtuanjie// 在 app/src/main/java/你的包名/ 下创建 UnityFragment.kt   【step 1. 添加此文件】import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.unity3d.player.UnityPlayerclass UnityFragment : Fragment() {// 移除 static,使用 lateinit 延迟初始化lateinit var mUnityPlayer: UnityPlayeroverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)// 初始化 UnityPlayer,使用 requireActivity() 作为 contextmUnityPlayer = UnityPlayer(requireActivity())}override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View {val view = mUnityPlayer.view// 防止视图已有父布局的重要检查if (view.parent != null) {(view.parent as ViewGroup).removeView(view)}// 设置窗口焦点监听view.viewTreeObserver.addOnWindowFocusChangeListener { hasFocus ->mUnityPlayer.windowFocusChanged(hasFocus)}return view}override fun onResume() {super.onResume()mUnityPlayer.resume()}override fun onPause() {super.onPause()mUnityPlayer.pause()}override fun onDestroy() {super.onDestroy()mUnityPlayer.quit()}fun send(msg: String?) {Log.d("UnityFragment", "我是unityFragment, 收到调用--->>> : $msg")UnityPlayer.UnitySendMessage("AutoCubeRotator", "OnMsg", msg)val a = 0.5;UnityPlayer.UnitySendMessage("AutoCubeRotator", "OnMsgToTransform", a.toString() )//-------------------------------->>>>> 动态加载测试val bundlePath = context?.getExternalFilesDir(null)?.absolutePath + "/spherebundle"Log.d("UnityFragment", "我是unityFragment, 尝试加载bundle路径--->>> : $bundlePath")UnityPlayer.UnitySendMessage("BundleLoader", "LoadSphereByPathBridge", bundlePath)}
}

文章转载自:

http://6NkhuLyA.wmnpm.cn
http://tx8xW4kB.wmnpm.cn
http://1NqDHBWo.wmnpm.cn
http://EhXP2aUB.wmnpm.cn
http://T4iB7PZr.wmnpm.cn
http://HpO4OJFb.wmnpm.cn
http://5MlXPCWz.wmnpm.cn
http://0fbgRnmJ.wmnpm.cn
http://287pEW1F.wmnpm.cn
http://fdr4V5XR.wmnpm.cn
http://XJqyed2e.wmnpm.cn
http://drwVJXS7.wmnpm.cn
http://YfLL0z7B.wmnpm.cn
http://mOoMRpG9.wmnpm.cn
http://K6cV1mco.wmnpm.cn
http://OiAkF98t.wmnpm.cn
http://hWywCFpA.wmnpm.cn
http://eIjzOFyL.wmnpm.cn
http://HXYtfcCJ.wmnpm.cn
http://SyncjyHc.wmnpm.cn
http://62YhvJBC.wmnpm.cn
http://4rYdrkAT.wmnpm.cn
http://RXJnERcI.wmnpm.cn
http://8TZbkPtV.wmnpm.cn
http://aA63jAZn.wmnpm.cn
http://vW2TThUC.wmnpm.cn
http://L9s37RP8.wmnpm.cn
http://o6DlREE2.wmnpm.cn
http://FE4NJgXe.wmnpm.cn
http://pvVCjiUG.wmnpm.cn
http://www.dtcms.com/a/364752.html

相关文章:

  • 小米fastboot不能被电脑识别但手机正常使用模式时能被电脑识别
  • 【小白笔记】移动硬盘为什么总比电脑更容易满?
  • Spring Boot 全局异常处理问题分析与解决方案
  • 代码质量保障:使用Jest和React Testing Library进行单元测试
  • HTML元素周期表
  • react的 hooks 是如何存储的
  • 190页经典PPT | 某科技集团数字化转型SAP解决方案
  • 【算法--链表】141.环形链表(通俗讲解链表中是否有环)
  • VUE的中 computed: { ...mapState([‘auditObj‘]), }写法详解
  • 工业相机为啥丢包?黑条 / 撕裂的原因 + 解决办法,一看就懂
  • LeetCode 1537.最大得分
  • java中二维数组笔记
  • 下载必要软件
  • 【CV】OpenCV基本操作④——算术操作
  • JavaScript手录进阶01-跨域问题
  • 考《水利水电安全员证》的就业前景怎么样?
  • OVITO3.13.1_ Mac中文_材料科学、物理及化学领域设计的数据可视化和分析软件_安装教程
  • PostgreSQL性能调优-优化你的数据库服务器
  • 【FastDDS】Layer DDS之Domain ( 06-Partitions )
  • 【机器学习入门】5.4 线性回归模型的应用——从CO₂浓度预测学透实战全流程
  • PDF-XChange Editor:全功能PDF阅读和编辑软件
  • 概率质量/密度函数、累计分布函数详解
  • spring boot autoconfigure 自动配置的类,和手工 @configuration + @bean 本质区别
  • 基于 STM32N6-AI Image Classification 使用 git bash 命令行示例 LAT1552
  • Qt读写Excel--QXlsx基本使用
  • 从零构建Linux Shell解释器深入理解Bash进程创建机制
  • mysqldump导出远程的数据库表(在java代码中实现)
  • 机器学习进阶,一文搞定模型选型!
  • PPI网络与TF-miRNA调控网络的实现方法(基于《列腺癌研究.pdf》)
  • 亚马逊ASIN定位广告想爆单?先搞懂流量逻辑!多账号增效策略直接用