我会说这个。我有一个游戏对象,它有一个精灵渲染器和一个粒子渲染器。我想要做的是,当我从脚本给它一个命令时,我想要游戏对象的精灵渲染器来改变材质,但是如果我这样做:`
using UnityEngine;
using System.Collections;
public class DoorBehav : MonoBehaviour {
public static float DoorHp = 100f;
public TextMesh HpText;
public Material brokenMat; //the material I want to use for the sprite renderer
private GameObject hero;
ParticleEmitter partEmit;
void Start () {
hero = GameObject.Find("Hero");
partEmit = GetComponent<ParticleEmitter> ();
HpText = transform.FindChild ("DoorHp").GetComponent<TextMesh>() as TextMesh;
HpText.color = Color.green;
}
void Update () {
if (Vector3.Distance (hero.transform.position, transform.position) < 1.8f)
{
HeroBehaviour.agent.speed = 0;
DoorHp-=1f;
partEmit.Emit();
HpText.text = ((Mathf.FloorToInt(DoorHp)).ToString()+"%");
if(DoorHp <=60f)
{
transform.renderer.material = brokenMat;
HpText.color = Color.yellow;
}
if(DoorHp <=30f)
{
HpText.color = Color.red;
}
if(DoorHp <=0)
{
//play sound : destroy door
HeroBehaviour.agent.speed = HeroBehaviour.moveSpeed;
Destroy(this.gameObject);
}
}
}
}
`
基本上,这是一扇门,当英雄靠近它时,它会失去hp(生命值)。如果hp变量低于60,则会将门的外观改为破门。然而,当我这样做时,它也会改变粒子渲染器的材质,它开始溢出微小的破碎的门,而不是破碎的门的derbis。我怎么才能只改变精灵渲染器的材质呢?我已经尝试了无数次,但我无法让它工作:(顺便说一句,我不能添加任何孩子到这个游戏对象,它会搞砸很多东西。提前感谢!:)
答案 0 :(得分:0)
我自己找到了解决办法。基本上,我做的是,我添加了一个ParticleRenderer并从游戏对象获得组件,就像我对粒子发射器一样。然后我为粒子渲染器导入了一个材质,在更改了精灵渲染器的材质后,我也更改了粒子渲染器:
using UnityEngine;
using System.Collections;
public class DoorBehav : MonoBehaviour {
public static float DoorHp = 100f;
public TextMesh HpText;
public Material brokenMat;
public Material particleMat;//the material for the particle renderer
private GameObject hero;
ParticleEmitter partEmit;
ParticleRenderer partRend;// the new particle renderer
void Start () {
hero = GameObject.Find("Hero");
partEmit = GetComponent<ParticleEmitter> ();
partRend = GetComponent<ParticleRenderer>();//importing the particle renderer
HpText = transform.FindChild ("DoorHp").GetComponent<TextMesh>() as TextMesh;
HpText.color = Color.green;
}
void Update () {
if (Vector3.Distance (hero.transform.position, transform.position) < 1.8f)
{
HeroBehaviour.agent.speed = 0;
DoorHp-=1f;
partEmit.Emit();
HpText.text = ((Mathf.FloorToInt(DoorHp)).ToString()+"%");
if(DoorHp <=60f)
{
transform.renderer.material = brokenMat;
partRend.material = particleMat;//changing the particle renderer's material
HpText.color = Color.yellow;
}
if(DoorHp <=30f)
{
HpText.color = Color.red;
}
if(DoorHp <=0)
{
//play sound : destroy door
HeroBehaviour.agent.speed = HeroBehaviour.moveSpeed;
Destroy(this.gameObject);
}
}
}
}