2016-04-01 7 views
1

単一のスクリプトを使用してUnity内の複数のゲームオブジェクトの色を変更したいと思います。私はちょっとそれをやる方法に迷っています。私はUnityの新人です。これは私にとって基本的な訓練の一種です。Unity 5で複数のゲームオブジェクトの色を変更する

Unityバージョン:5.3.4

観察された行動:

は、他のゲームオブジェクトに同じスクリプトと同じ色にすべての変更

予想される動作を追加しました

ゲームオブジェクトの色を個別に変更する

試した事の

一覧:-FindGameObject-

を使用して

が同時に

複数のスクリプトで考えるの両方を試してみました-GameObject-

を使用して材料をアクセスもしようとしました私が望む結果を達成するために

コード

C#の:私はUnityへの新たなんだ言ったように

using UnityEngine; 
using System.Collections; 

public class ChangeColor : MonoBehaviour 
{ 
    //If I change these variables to -GameObject- 
    //It blocks me to access the renderer 
    //Making the variables public doesn't work either 
    private Renderer cube; 
    private Renderer sphere; 

void Start() 
{ 
    //Tried here the -FindGameObjectWithTag- 
    cube = GetComponent<Renderer>(); 
    sphere = GetComponent<Renderer>(); 
} 

void Update() 
{ 
    if(Input.GetKeyDown(KeyCode.A)) 
    { 
     //Tried here the -FindGameObjectWithTag- 
     cube.material.color = Color.red; 
    } 

    if(Input.GetKeyDown(KeyCode.S)) 
    { 
     //Tried here the -FindGameObjectWithTag- 
     sphere.material.color = Color.green; 
    } 
    } 
} 

は、たぶん私は、何か間違ったことをやって、それがnoobfriendly優れている場合、私は親切に、任意の助けを受け入れます。

ありがとうございました

答えて

0

これについては、いくつかの方法があります。

1)彼らはあなたが子供を通じてあまりにもそこに他のオブジェクトなしで同じ親の下にあるすべてのループ可能性があると

GameObject Parent = GameObject.Find("ParentObject"); 
for(int x = 0; x > Parent.transform.childCount; x++); 
{ 
    Parent.transform.getChild(x).GetComponent<Renderer>().material.color = Color.red; 
} 

2自分の色を変更した場合)20ishと言うよりも少ないがある場合は、あなたが作成することができますリストのサイズを持っているオブジェクトの数に変更した後、各トランスフォームをインスペクタにドラッグ&ドロップするだけです。あなたはコードでそれをすべて行いたい場合は、

//Outside function 
public List<Transform> Objs; 
//inside function 
Objs.Add(GameObject.Find("FirstObject").transform); 
Objs.Add(GameObject.Find("SecondObject").transform); 
//... keep doing this 
//now do the same foreach loop as in 2 

4)あなたは、オブジェクトの多くを持っている場合は、(タグで検索できます)(私を行うことができます2と同様に

/*Make sure you have Using "System.Collections.Generic" at the top */ 
//put this outside function so that the inspector can see it 
public List<Transform> Objs; 
// in your function put this (when changing the color) 
foreach(Transform Tform in Objs){ 
    Tform.GetComponent<Renderer>().material.color = Color.red; 
} 

3)、

//Outside function 
public GameObject[] Objs; 
//inside function 
Objs = GameObject.FindGameObjectsWithTag("ATagToChangeColor"); 

foreach(Transform Tform in Objs){ 
    Tform.GetComponent<Renderer>().material.color = Color.red(); 
} 

そして、このコメントについて)それは、各コンポーネントを通過しているが、私はそれをバックアップする証拠がないという理由だけで、これは少し時間がかかるだろうと想像:

//私は私がレンダラ変数の国民は

場合はどちらか動作しません作る

//にアクセスするために-GameObject-

//このブロックにこれらの変数を変更した場合GameObject型にすると、簡単にレンダラーにアクセスできます。

public GameObject cube; 
public void Start(){ 
    cube.GetComponent<Renderer>().material.color = Color.red(); 
} 

変数をパブリックにすると、統一のインスペクタは変数を見ることができ、スクリプトを開かなくても統一エディタで変数を変更することができます。

関連する問題