2017-02-13 56 views
0

我在Assert中有兩個預製件;在我的場景中,我有兩個預製件的實例。我試圖用按鈕單擊來改變一個預製件的所有實例的顏色,但是我得到的結果是兩個預製件的所有實例的顏色都改變了。我如何指定在特定功能內更改預製件?我猜gameObject是指我場景中的所有gameObjects,可能這就是爲什麼所有的實例都會改變顏色。更改預製實例的顏色

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

public class eventSensors : MonoBehaviour { 


    // Use this for initialization 
    void Start() { 

    } 

    // Update is called once per frame 
    void Update() { 

    } 

    public void tempSensor() { 

     print("estas en la funcuion de tempSensor"); 
     // this.gameObject.GetComponent<Renderer>().material.color = Color.red; 
     //gameObject.GetComponent<Renderer>().sharedMaterial.color = Color.red; 
    var prefab=  Instantiate(gameObject, transform.position, transform.rotation); 

     prefab.GetComponent<Renderer>().material.SetColor("_Color", Color.red); 
    } 
    public void lightSensor() 
    { 
     print("estas en la funcuion de lightSensor"); 
     gameObject.GetComponent<Renderer>().sharedMaterial.color = Color.green; 

    } 
    //Sent to all game objects before the application is quit 
    //this is called when the user stops playmode. 
    private void OnApplicationQuit() 
    { 
     //reset all prefab color to default 
     gameObject.GetComponent<Renderer>().sharedMaterial.color = Color.white; 
    } 
} 
+0

是的,我只有一個單一的材料文件夾中的proyect –

+0

無需創建多個材料:看我的答案。 – Kardux

+0

建議:發佈你的問題,關於你如何使ti工作作爲你的問題的答案。 – starbeamrainbowlabs

回答

1

只需要求GetComponent<Renderer>().material.color代替:Renderer.material返回材料,而不是共享的一個實例。

當Renderer包含多種材質時,您可以使用GetComponent<Renderer>().materials[i]而不是GetComponent<Renderer>().sharedMaterials[i]來調用相同的方法。

作爲便箋,gameObject.GetComponent<>()可以簡化爲GetComponent<>(),因爲您的腳本繼承自MonoBehaviour

希望這有助於

+0

我想通過創建一個數組來保存預製件的所有實例,然後使用一個foreach函數來迭代這些實例並使用MeshRenderer改變那裏的顏色。 'public GameObject [] getCount; getCount = GameObject.FindGameObjectsWithTag(「tempPrefabTag」); int count; count = getCount.Length; 的foreach(遊戲物體○在getCount將) { //爲了存取權限原料成分使用:MeshRenderer //改變每個遊戲物體的顏色在預製 o.GetComponent ()material.SetColor( 「_顏色」 , 紅色); } }' –

+0

很高興幫助!我編輯了你的問題來添加你的答案,以便閱讀比評論更容易。如果你覺得這個答案是正確的,請選擇它作爲答案。 – Kardux