在游戏中,经常要用到被点击的物体或者被碰触的物体需要改变颜色状态,介绍一个简单实用的技巧。

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用法的可以在以后有时间给大家附上一篇解释。

相关文章:

  • 2021-04-10
  • 2021-08-24
  • 2021-09-29
  • 2021-04-29
  • 2022-12-23
  • 2021-08-28
  • 2021-07-21
  • 2021-09-30
猜你喜欢
  • 2021-04-29
  • 2021-10-10
  • 2021-10-09
  • 2021-10-18
  • 2021-10-03
  • 2021-12-05
相关资源
相似解决方案