2017-08-27 12 views
2

私は、オブジェクトを連続的に生成し、生成されたすべてのオブジェクトにスクリプトを添付するスクリプトを作成しようとしています。 3秒後に添付されたスクリプトを作成し、オブジェクトのマテリアルを変更して、ボックスコライダーを追加します。私の問題は材料にあります。オブジェクトはランダムに生成されているので、マテリアル変数を設定する方法はわかりません。Unity - ゲームオブジェクトにマテリアルを追加

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

このようにpublic static 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" からそれを読み込むことができます:これは私のスポーナプログラムです:

​​3210

そして、これは添付ますスクリプトです、typeof(Material))をマテリアルとして使用します。

+0

この答えは間違っています。 [Unity Documentation](https://docs.unity3d.com/ScriptReference/Resources.Load.html)によると、拡張は省略されなければならない。 –

関連する問題