脚本可作为文本资源 (TextAssets) 添加至资源包 (AssetBundles),但实际上,如此情况下的脚本将成为不可运行的代码。如需在资源包 (AssetBundles) 中添加可在应用程序中运行的代码,则需要将其预编译为程序集,并使用 Mono 映射 (Reflection) 类加载程序集(注意:映射不适用于 iOS)。您可在任意普通的 C# 集成开发环境 (IDE)(如 Monodevelop,Visual Studio)中创建程序集,或使用 mono/.net 编译器创建任何文本编辑器。
string url = "http://www.mywebsite.com/mygame/assetbundles/assetbundle1.unity3d"; IEnumerator Start () { // Start a download of the given URL WWW www = WWW.LoadFromCacheOrDownload (url, 1); // Wait for download to complete yield return www; // Load and retrieve the AssetBundle AssetBundle bundle = www.assetBundle; // Load the TextAsset object TextAsset txt = bundle.Load("myBinaryAsText", typeof(TextAsset)) as TextAsset; // Load the assembly and get a type (class) from it var assembly = System.Reflection.Assembly.Load(txt.bytes); var type = assembly.GetType("MyClassDerivedFromMonoBehaviour"); // Instantiate a GameObject and add a component with the loaded class GameObject go = new GameObject(); go.AddComponent(type); }
Page last updated: 2013-06-26