简体   繁体   中英

Change color of prefab instances

I have two prefabs in my Assert; in my scene I have instances of the two prefabs. I am trying to change the color of all the instances of one prefab with a button click but what I get is that the color of all the instances of the two prefabs changes. How can I indicate the prefab to change inside a specific function? I'm guessing gameObject is referring to all the gameObjects in my scene and probably thats why all the instances change color.

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;
    }
}

Simply call for GetComponent<Renderer>().material.color instead: Renderer.material returns the instance of the material instead of the shared one.

The same way you can call for GetComponent<Renderer>().materials[i] instead of GetComponent<Renderer>().sharedMaterials[i] when your Renderer contains multiple materials.

As a side note, the gameObject.GetComponent<>() can be simplified to GetComponent<>() since your script inherit from MonoBehaviour .

Hope this helps,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM