当前位置: 首页 > 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://www.xdnf.cn/news/1447669.html

相关文章:

  • Android创建demo脚本
  • CSS中使用 HSL(Hue, Saturation, Lightness) 动态生成色值
  • Linux 对目录授予用户读写权限的方法
  • 信创MySQL到达梦数据库的SQL语法转换技术解析
  • AWK命令完全指南:从理论到实战的文本处理利器
  • Spring Boot + Nacos 配置中心示例工程
  • tcpdump用法
  • Best Video网页官网入口 – 免费在线网页视频解析下载器
  • 认识HTML
  • 用资产驱动方法构建汽车网络安全档案
  • VPS云服务器安全加固指南:从入门到精通的全面防护策略
  • TypeScript 内置工具类型大全(ReturnType、Omit、Pick 等)
  • 【Unity项目经验分享】实现左右分屏裸眼3D程序
  • 数据结构之加餐篇 -顺序表和链表加餐
  • 从 0 到 1 实现 PyTorch 食物图像分类:核心知识点与完整实
  • 基础看门狗--idf开发esp32s3
  • PNP具身解读——RSS2025论文加州伯克利RLDG: 通过强化学习实现机器人通才策略提炼。
  • 基于物联网的智慧用电云平台构建与火灾防控应用研究
  • 复杂网络环境不用愁,声网IoT多通道传输实战经验丰富
  • Coze使用教程-插件
  • 袋鼠云产品功能更新报告14期|实时开发,效率再升级!
  • Kafka面试精讲 Day 6:Kafka日志存储结构与索引机制
  • 浏览器插件开发--通过调用本地nmap实现nmap插件扫描
  • python如何解决html格式不规范问题
  • Android使用内存压力测试工具 StressAppTest
  • [嵌入式embed][Qt]Qt5.12+Opencv4.x+Cmake4.x_用Qt编译linux-Opencv库 测试
  • 显存与内存
  • 【甲烷数据】MethaneSAT 卫星遥感数据
  • 使用DCGAN实现动漫图像生成
  • 树莓集团产教融合:数字学院践行职业教育“实体化运营”要求