Unity Sprite淡入淡出速度 [英] Unity sprite fade in and out speed

查看:621
本文介绍了Unity Sprite淡入淡出速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图统一循环一个精灵的淡入和淡出.我是Unity和C#的新手.

I am trying to loop a fade-in and fade-out of a sprite in unity. I am new to Unity and C#.

我当前的代码:

public float minimum = 0.0f;
public float maximum = 1f;
public float duration = 50.0f;

public bool faded = false;

private float startTime;
public SpriteRenderer sprite;

void Start () {
    startTime = Time.time;
}

void Update () {
    float t = (Time.time - startTime) / duration;

    if (faded) {
        sprite.color = new Color(1f, 1f, 1f, Mathf.SmoothStep(minimum, maximum, t));
        if (t > 1f) {
            faded = false;
            startTime = Time.time;
        }
    } else {
        sprite.color = new Color(1f, 1f, 1f, Mathf.SmoothStep(maximum, minimum, t));
        if (t > 1f) {
            faded = true;
            startTime = Time.time;
        }
    }
}

这有效,但是它太慢了,我希望使淡入更快,并且淡出比淡入慢一些.我该如何更新我的代码?

This works but it is too slow, I wish to make the fade in faster and the fade out a bit slower than the fade in. Something of the effect of a heartbeat. How do I update my code for that?

还有,对此有更好的方法吗?我认为Update()上的NEW过多会导致内存泄漏.

Also, is there a better approach to this? I think i'll get a memory leak with the too much NEW on the Update().

关于安德鲁给出的内容,我尝试调试他的代码:

As for what Andrew has given, I tried to debug his code:

    } else {
        sprite.color = new Color(1f, 1f, 1f, Mathf.Lerp(sprite.color.a, minimum, step));
        print (Mathf.Abs(sprite.color.a - minimum));
        print (threshold);

告诉我:

 2.206551E-20 // Mathf.Abs()?
 1.401298E-45 // threshold?

推荐答案

不要担心Update()中的new,因为Color是值类型,并且C#善于处理垃圾回收

Dont worry about the new in the Update(), because Color is a value type, and C# is good at handling garbage collection

public float minimum = 0.0f;
public float maximum = 1f;
public float speed = 5.0f;
public float threshold = float.Epsilon;

public bool faded = false;

public SpriteRenderer sprite;

void Update () {
    float step = speed * Time.deltaTime;

    if (faded) {
        sprite.color = new Color(1f, 1f, 1f, Mathf.Lerp(sprite.color.a, maximum, step));
        if (Mathf.Abs(maximum - sprite.color.a) <= threshold)
            faded = false;

    } else {
        sprite.color = new Color(1f, 1f, 1f, Mathf.Lerp(sprite.color.a, minimum, step));
        if (Mathf.Abs(sprite.color.a - minimum) <= threshold)
            faded = true;
    }
}

此外,如果您只关心淡入淡出效果,则只需一行即可:

Also, if all you care about is a fade in-out effect, all you need is a single line:

public float max = 1f;
public float speed = 5.0f;

public SpriteRenderer sprite;

void Update () {
    sprite.color = new Color(1f, 1f, 1f, Mathf.PingPong(Time.time * speed, max));
}

这篇关于Unity Sprite淡入淡出速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆