分享個Unity 遊戲體縮放和透明閃爍的動畫原始碼,方便大家不用重複造輪子。
遊戲體縮放原始碼
。using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TweenScale : MonoBehaviour {
private float tween;
private bool sign;
void Start()
{
tween = 1;
sign = true;
}
void Update()
{
//print(tween);
if (sign == false)
{
if (tween > 0.8f)
{
this.gameObject.GetComponent<Transform>().localScale = new Vector3(tween, tween, 1);
tween = tween - 0.008f;
}
else sign = true;
}
if (sign)
{
if (tween < 1.2f)
{
this.gameObject.GetComponent<Transform>().localScale = new Vector3(tween, tween, 1);
tween = tween + 0.008f;
}
else sign = false;
}
}
}
Image或text透明閃爍的動畫原始碼
。using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TweenAlpha : MonoBehaviour {
private Image tweenAlpha_Image;
private Text tweenAlpha_Text;
private float tween ;
private bool sign;
/// <summary>
/// 閃爍速度
/// </summary>
public float speed = 7;
/// <summary>
/// 透明度最低值
/// </summary>
public float alphaMin = 50;
//變化的顏色 RGBA值
public float R = 255;
public float G =255;
public float B = 255;
private bool imageSign = true;
void Start()
{
tweenAlpha_Image = this.gameObject.GetComponent<Image>();
if (tweenAlpha_Image == null) {
tweenAlpha_Text = this.gameObject.GetComponent<Text>();
imageSign = false;
}
tween = 255;
sign = true;
}
void Update()
{
if (imageSign)
{
if (sign)
{
if (tween > alphaMin)
{
tweenAlpha_Image.color = new Color(R / 255f, G / 255f, B / 255f, tween / 255f);
tween = tween - speed;
}
else sign = false;
}
if (sign == false)
{
if (tween < 255)
{
tweenAlpha_Image.color = new Color(R / 255f, G / 255f, B / 255f, tween / 255f);
tween = tween + speed;
}
else sign = true;
}
}
else
{
if (sign)
{
if (tween > alphaMin)
{
tweenAlpha_Text.color = new Color(R / 255f, G / 255f, B / 255f, tween / 255f);
tween = tween - speed;
}
else sign = false;
}
if (sign == false)
{
if (tween < 255)
{
tweenAlpha_Text.color = new Color(R / 255f, G / 255f, B / 255f, tween / 255f);
tween = tween + speed;
}
else sign = true;
}
}
}
}
帶有SpriteRenderer元件的遊戲體透明閃爍的動畫原始碼
。using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TweenAlpha : MonoBehaviour {
private SpriteRenderer tweenAlpha;
private float tween ;
private bool sign;
void Start()
{
tweenAlpha = this.gameObject.GetComponent<SpriteRenderer>();
tween = 255;
sign = true;
}
void Update()
{
if (sign)
{
if (tween > 50)
{
tweenAlpha.color = new Color(1, 1, 1, tween / 255f);
tween = tween - 6f;
}
else sign = false;
}
if (sign == false)
{
if (tween < 255)
{
tweenAlpha.color = new Color(1, 1, 1, tween / 255f);
tween = tween + 6f;
}
else sign = true;
}
}
}