UNITY UGUI 自动更新贴图ALPHA

原文

玉田!来!永强哥教你写点小逻辑!嘤嘤嘤。。。

同上节课一样的图片+按钮,目标是实现点击按钮后自动更新图片的Alpha值。

今天需要写两个脚本

ClassA:MyFace.cs
usingSystem.Collections;
usingSystem.Collections.Generic;usingUnityEngine;
usingUnityEngine.UI;
public class MyFace:MonoBehaviour
{
    [SerializeField]
    public Image m_image;
    [SerializeField]
    public boolm_updateAlpha =false;
    [MyFloatAttribute(1.0f, 0f)]
    public floatm_updateAlphaValue =0.5f;
    publicfloatm_currAlphaValue =0.5f;
    privateintm_alpahDir =1;
    publicvoidAlphaUpdate()    
    {        
        m_updateAlpha = !m_updateAlpha;    
    }
    // Start is called before the first frame update
    voidStart()    
    {        
        m_currAlphaValue = m_image.canvasRenderer.GetAlpha();    
    }
    // Update is called once per frame
    void Update()    
    {
        if(m_updateAlpha)        
        {            
            m_currAlphaValue = m_currAlphaValue + m_updateAlphaValue * Time.deltaTime * m_alpahDir;
            if(m_currAlphaValue >=1)           
             {
                m_currAlphaValue =1;
                m_alpahDir *=-1;           
            }
            elseif(m_currAlphaValue <=0)            
            {
                m_currAlphaValue =0;
                m_alpahDir *=-1;            
            }            
            m_image.canvasRenderer.SetAlpha(m_currAlphaValue) ;       
        }          
    }
}

ClassB:MyFloatAttribute.cs

usingSystem.Collections;
usingSystem.Collections.Generic;
usingUnityEngine;

public classMyFloatAttribute:PropertyAttribute
{
    publicfloatfloatMax;
    publicfloatfloatMin;

    publicMyFloatAttribute(floatmax,floatmin)    
    {        
        floatMax = max;        
        floatMin = min;    
    }
}

这个Class 的作用是在Inspector中 Class的Public成员变量 float类型限定取值范围。比方说100-0,默认值为0.5

[MyFloatAttribute(100.0f, 0f)]
public floatm_updateAlphaValue =0.5f;

下面是编辑器操作的部分

在Hierarchy中选中Image

在Inspector中点击最下面的“Add Component”按钮

添加MyFace西萨婆脚本,并且将Hierarchy中的Image拖到MyFace的Image中去

好了现在可以运行了。嘤嘤嘤。。。

以上有个按钮点击事件没有提到 如果不知道怎么实现的请看我前面的帖子
Unity UGUI 自定义监听事件函数
UNITY UGUI Event Trigger
原文

你可能感兴趣的:(UNITY UGUI 自动更新贴图ALPHA)