C# 更改预设实例的颜色
我的断言中有两个预设;在我的场景中,我有两个预制件的实例。我试图通过点击按钮来改变一个预置的所有实例的颜色,但是我得到的是两个预置的所有实例的颜色都改变了。如何在特定函数中指示要更改的预置?我猜gameObject指的是我场景中的所有游戏对象,可能这就是为什么所有实例都会改变颜色C# 更改预设实例的颜色,c#,unity3d,unity5,C#,Unity3d,Unity5,我的断言中有两个预设;在我的场景中,我有两个预制件的实例。我试图通过点击按钮来改变一个预置的所有实例的颜色,但是我得到的是两个预置的所有实例的颜色都改变了。如何在特定函数中指示要更改的预置?我猜gameObject指的是我场景中的所有游戏对象,可能这就是为什么所有实例都会改变颜色 using System.Collections; using System.Collections.Generic; using UnityEngine; public class eventSensors : M
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;
}
}
使用系统集合;
使用System.Collections.Generic;
使用UnityEngine;
公共类事件传感器:单行为{
//用于初始化
无效开始(){
}
//每帧调用一次更新
无效更新(){
}
公共传感器(){
打印(“临时传感器的功能”);
//this.gameObject.GetComponent().material.color=color.red;
//gameObject.GetComponent().sharedMaterial.color=color.red;
var prefab=实例化(游戏对象、transform.position、transform.rotation);
prefact.GetComponent().material.SetColor(“\u Color”,Color.red);
}
公共光传感器()
{
打印(“光传感器的功能”);
gameObject.GetComponent().sharedMaterial.color=color.green;
}
//在退出应用程序之前发送到所有游戏对象
//当用户停止播放模式时,将调用此选项。
Application Quit()上的私有void
{
//将所有预设颜色重置为默认值
gameObject.GetComponent().sharedMaterial.color=color.white;
}
}
只需调用GetComponent().material.color
即可:Renderer.material
返回材质实例而不是共享实例
同样,当渲染器包含多个材质时,可以调用GetComponent().materials[i]
而不是GetComponent().sharedMaterials[i]
作为旁注,gameObject.GetComponent()
可以简化为GetComponent()
,因为您的脚本继承自monobhavior
希望这有帮助,是的,我在项目中只有一个材质文件夹,不需要创建多个材质:请参见我的答案。建议:发布您关于如何使ti工作的问题,作为您问题的答案。我通过创建一个数组来保存预制件的所有实例,从而解决了这个问题,然后使用foreach函数迭代这些实例,并使用MeshRenderer更改这些实例的颜色<代码>公共游戏对象[]getCount;getCount=GameObject.FindGameObjectsWithTag(“tempPrefableTag”);整数计数;count=getCount.Length;foreach(getCount中的GameObject o){//访问材质组件使用:MeshRenderer//更改预置o.GetComponent().material.SetColor(_color),color.red);}}很高兴这有帮助!我编辑了你的问题,添加了你的答案,这样比在评论中更容易阅读。如果您觉得这个答案是正确的,请选择它作为答案。