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:\Personal\My Documents\Projects\TestLib\TestLib\bin\Release\TestLib.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安裝根目錄\Unity\Editor\Data\Managed/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);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM