简体   繁体   English

更改预制实例的颜色

[英]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. 我猜想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;
    }
}

Simply call for GetComponent<Renderer>().material.color instead: Renderer.material returns the instance of the material instead of the shared one. 只需调用GetComponent<Renderer>().material.colorRenderer.material返回材质的实例,而不是共享的实例。

The same way you can call for GetComponent<Renderer>().materials[i] instead of GetComponent<Renderer>().sharedMaterials[i] when your Renderer contains multiple materials. 当渲染器包含多种材质时,可以使用相同的方法来调用GetComponent<Renderer>().materials[i]而不是GetComponent<Renderer>().sharedMaterials[i]

As a side note, the gameObject.GetComponent<>() can be simplified to GetComponent<>() since your script inherit from MonoBehaviour . 附带说明一下,由于您的脚本继承自MonoBehaviour ,因此gameObject.GetComponent<>()可以简化为GetComponent<>()

Hope this helps, 希望这可以帮助,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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