Using code to control object transparency in Unity (object flickering simple version)

I have read many articles before, and some of them are not very friendly to friends who just want to simply use code to control the transparency of objects, such as me. So after researching for a long time, I found a very simple method. I share it here with beginners who want to use it. I hope it can help you and record it as a note for yourself.

The first step is to create a new material ball:

Step 2: Set Fade. Only by setting it can the transparency of objects using this material be controlled by the Alpha value.

Step 3: Click the color bar to customize the color you want

And we need to make it clear that what we want to control is the Alpha value in Color. The value of Alpha is represented in the code by the range from 0 to 1.

 Step 4: Create a Cube. Of course, other objects can also be used. Drag the material ball created in the previous step into the object.

Step 5: Add control script: Just add it directly to the object

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Alphas : MonoBehaviour
{
    //控制材质球的Alpha值,设为1让物体可见
    public float  alpha=1;
    //变化速率
    public float rate=0.1f;
    //控制闪烁的开关
    public bool change;

    void Update()
    {
       
        Timer();
    }
    //控制物体闪烁
    public void Timer()
    { 
        //限制alpha的值在0到1之间
        alpha = Mathf.Clamp(alpha, 0, 1);
        //实时更新Alpha值,否则无法起作用
        this.gameObject.GetComponent<MeshRenderer>().material.color = new Color(1, 0.3f, 0, alpha);
        if (change)
        {
            alpha += rate * Time.deltaTime;
            if (alpha>=1)
            {
                alpha = 1;
                change = false;
            }
        }
        else
        {
            alpha -= rate * Time.deltaTime;
            if (alpha <= 0)
            {
                alpha = 0;
                change = true;
            }

        }
    }
}

Final effect demonstration: controlling the flashing frequency by changing the rate
 

 

 

 

Guess you like

Origin blog.csdn.net/KKKKKzhu/article/details/131991390