unity3d中给GameObject绑定脚本的代码

一、获取GameObject

1.GameObject.Find()

通过场景里面的名子或者一个路径直接获取游戏对象。
    GameObject root = GameObject.Find(“GameObject”);

我觉得如果游戏对象没再最上层,那么最好使用路径的方法,因为有可能你的游戏对象会有重名的情况,路径用“/”符号隔开即可。
    GameObject root = GameObject.Find(“GameObject/Cube”);

二、添加或删除一个脚本

//tempQie2为GameObject,qiemove为自定义的脚本类名称  
  
tempQie2.AddComponent<qiemove>();//添加绑定脚本  
  
Destroy(tempQie2.GetComponent("qiemove"));//删除绑定脚本  
  
//如果添加其他属性,可AddComponent<其他类定义>();  

三、动态加载一个(外部)脚本

var fs = new FileStream(@"D:PersonalMy DocumentsProjectsTestLibTestLibinReleaseTestLib.dll", FileMode.Open);  
 var b = new byte[fs.Length];  
 fs.Read(b, 0, b.Length);  
 fs.Close();  
 var assembly = System.Reflection.Assembly.Load(b);  
 var type = assembly.GetType("Test");  
 gameObject.AddComponent(type); 

分析这段代码

加载里一个DLL,这个DLL实际上是用C#打包的代码库,关于对库的各种叫法实在让人蛋疼,不提也罢。总之建立一个工程然后引用U3D的库UnityEngine.dll就可以编译,不引用UnityEngine.dll当然首先就没法通过编译。

我这里的类名就叫Test,所以获取类型就是这样的。这里添加组件就不能用AddComponent(string)方法,那样会提示找不到了,可能这个方法只是从字典里面找到相应的类型然后在用AddComponent(type)来添加。

要吐槽的是关于那个二进制流。看网上很多WWW来读取TextAsset然后转成byte[]。事实上我不管怎么试都是失败。与干脆用C#自带的函数,就实际情况来说虽然统一使用WWW会比较方便,不过即使用C#来做网络下载难度也不会太大。

补充:WINDOWS下可以用        var assembly = System.Reflection.Assembly.LoadFile(@"D:TestLib1.dll");

Andriod下只能用      var assembly = System.Reflection.Assembly.Load(b);

  2) (未试过)

本文记录如何通过unity3d进行脚本资源打包加载

a、创建TestDll.cs文件

public class TestDll : MonoBehaviour {
    void Start () {
        print("Hi U_tansuo!");
    }
}

b、生成dll文件

   (1)使用vs打包

  (2) 使用mono打包

    (3) 命令行打包 mac下(亲测):  /Applications/Unity/Unity.app/Contents/Frameworks/Mono/bin/gmcs -r:/Applications/Unity/Unity.app/Contents/Frameworks/Managed/UnityEngine.dll -target:library 脚本路径

                        win下(未试过):mcs -r: /unity安装根目录UnityEditorDataManaged/UnityEngine.dll -target:library 脚本路径

c、更改文件后缀

      至关重要一步  更改上一步生成的TestDLL.dll 为 TestDLL.bytes  否则 打包加载会错

d、使用 BuildPipeline.BuildAssetBundle进行打包 资源为 TestDll.unity3d

e、加载

    IEnumerator Test()
    {
    
            string url="file://"+Application.dataPath+"/TestDll.unity3d";
        print(url);
          WWW www = WWW.LoadFromCacheOrDownload (url, 1);

    // Wait for download to complete
    yield return www;
        
    // Load and retrieve the AssetBundle
    AssetBundle bundle = www.assetBundle;
//TestDll 是资源的名字
        TextAsset txt = bundle.Load("TestDll", typeof(TextAsset)) as TextAsset;
        print(txt.bytes.Length);
    // Load the assembly and get a type (class) from it
    var assembly = System.Reflection.Assembly.Load(txt.bytes);
    var type = assembly.GetType("TestDll");

    // Instantiate a GameObject and add a component with the loaded class
    
    gameObject.AddComponent(type);
    }
原文地址:https://www.cnblogs.com/eniac1946/p/7233640.html