Practical tips for brightening objects in games

In the game, it is often necessary to use the clicked object or the touched object to change the color state. A simple and practical technique is introduced.

1. Add a material to the object, and the material must have color attributes. (For the traditional shader transformation, please refer to my shader transformation article)

2. Add a script to the object.

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;
    }
}

The key to the script I use is

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;
        }

Transition from white to its own color in turn. For other parts of the network, don't look at those that are not needed.

If you still don't know the usage of IEnumerator and yield, you can attach an explanation in the future.

Guess you like

Origin blog.csdn.net/qq_23158477/article/details/105224541