2017-08-27 72 views
2

我正在嘗試創建一個腳本,它不斷生成對象並將腳本附加到所有生成的對象。我希望附加的腳本在3秒後更改對象上的材質並添加框對撞機。我的問題在於材料。由於對象是隨機生成的,我不知道如何設置材質變量。這是我的產卵:Unity - 將材質添加到遊戲對象

​​3210

這是獲取連接的腳本:

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class Astroid : MonoBehaviour { 
    //I need to be able to set this variable to a material 
    public Material mat; 
    // Use this for initialization 
    void Start() { 
     this.GetComponent<SphereCollider>().enabled = false; 
     StartCoroutine("Change"); 
    } 
    // Update is called once per frame 
    void Update() { 

    } 
    IEnumerator Change(){ 
     yield return new WaitForSeconds (3); 
     this.GetComponent<SphereCollider>().enabled = true; 
     this.GetComponent<Renderer>().material = mat; 
    } 
} 

回答

0

你可以像這樣做一個公共的靜態int。 您的產卵:

public Material mat; 
 
public static Material mat2; 
 
void Start(){ 
 
mat2 = mat; 
 
}

而在你的星形線的腳本:

using System.Collections; 
 
using System.Collections.Generic; 
 
using UnityEngine; 
 

 
public class Astroid : MonoBehaviour { 
 
\t //I need to be able to set this variable to a material 
 
\t //public Material mat; 
 
\t // Use this for initialization 
 
\t void Start() { 
 
\t \t this.GetComponent<SphereCollider>().enabled = false; 
 
\t \t StartCoroutine("Change"); 
 
\t } 
 
\t // Update is called once per frame 
 
\t void Update() { 
 
\t \t 
 
\t } 
 
\t IEnumerator Change(){ 
 
\t \t yield return new WaitForSeconds (3); 
 
\t \t this.GetComponent<SphereCollider>().enabled = true; 
 
\t \t this.GetComponent<Renderer>().material = Spawner.mat2; 
 
\t } 
 
}

1

你可以只從資源

墊= Resources.Load( 「myMaterial.mat」 加載,typeof(Material))作爲材料;

+0

這個答案是不正確。根據[Unity文檔](https://docs.unity3d.com/ScriptReference/Resources.Load.html),擴展名必須省略。 –