在游戏中,经常要用到被点击的物体或者被碰触的物体需要改变颜色状态,介绍一个简单实用的技巧。
1.物体添加一个材质,材质要有颜色属性。(传统的shader改造请参考我的shader改造那一篇)
2.在物体上添加脚本。
using System.Collections;
using UnityEngine;
public class OnClickFlashRpc : Photon.PunBehaviour
{
private Material originalMaterial;
private Color originalColor;
private bool isFlashing;
// called by InputToEvent.
// we use this GameObject's PhotonView to call an RPC on all clients in this room.
private void OnClick()
{
photonView.RPC("Flash", PhotonTargets.All);
}
// A PUN RPC.
// RPCs are only executed on the same GameObject that was used to call it.
// RPCs can be implemented as Coroutine, which is here used to flash the emissive color.
[PunRPC]
private IEnumerator Flash()
{
if (isFlashing)
{
Debug.Log("for outside00.");
yield break;
}
isFlashing = true;
Debug.Log("for outside.11");
this.originalMaterial = GetComponent<Renderer>().material;
if (!this.originalMaterial.HasProperty("_Emission"))
{
Debug.LogWarning("Doesnt have emission, can't flash " + gameObject);
yield break;
}
this.originalColor = this.originalMaterial.GetColor("_Emission");
this.originalMaterial.SetColor("_Emission", Color.white);
for (float f = 0.0f; f <= 1.0f; f += 0.08f)
{
Color lerped = Color.Lerp(Color.white, this.originalColor, f);
this.originalMaterial.SetColor("_Emission", lerped);
yield return null;
}
this.originalMaterial.SetColor("_Emission", this.originalColor);
isFlashing = false;
}
}
我用的脚本中关键的就是
for (float f = 0.0f; f <= 1.0f; f += 0.08f)
{
Color lerped = Color.Lerp(Color.white, this.originalColor, f);
this.originalMaterial.SetColor("_Emission", lerped);
yield return null;
}
依次从白色过渡到自身颜色。其他网络部分,不需要的可以不看。
如果还有不清楚IEnumerator和yield用法的可以在以后有时间给大家附上一篇解释。