如何在OnMouseUp Event中执行某些操作之前等待几秒钟

时间:2014-10-28 13:27:41

标签: c# unity3d

我正在编写带有动画的游戏,并在用户点击按钮时使用这些动画。我想向用户展示动画,而不是"只是"使用Application.loadLevel调用新级别。我以为我可以在onMouseUp方法中使用Time.DeltaTime并将其添加到预定义的0f值,然后检查它是否大于(例如)1f,但它只是因为onMouseUp方法添加而无法工作"它自己的时间"作为增量时间。

我的脚本现在看起来像这样:

public class ClickScriptAnim : MonoBehaviour {

public Sprite pressedBtn;
public Sprite btn; 
public GameObject target;
public string message;
public Transform mesh;
private bool inAnim = true;
private Animator animator;
private float inGameTime = 0f;

// Use this for initialization
void Start () {
    animator = mesh.GetComponent<Animator>();
}



// Update is called once per frame
void Update () {

}

void OnMouseDown() {
    animator.SetBool("callAnim", true);

}

void OnMouseUp() {
    animator.SetBool("callAnim", false);
    animator.SetBool("callGoAway", true);
    float animTime = Time.deltaTime;

    Debug.Log(inGameTime.ToString());
// I would like to put here something to wait some seconds
        target.SendMessage(message, SendMessageOptions.RequireReceiver);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我不完全确定你在onMouseUp中使用Time.deltaTime想要做什么。这只是自上一帧渲染以来的秒数,无论您在何处尝试访问它,都应该采取相同的行动。通常它用在每个帧调用的函数中,而不是像onMouseUp那样的一次性事件。

尽管不确定你想要实现什么,但听起来你应该使用Invoke:

http://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html

只需将您希望延迟的代码放入单独的函数中,然后在onMouseUp中延迟调用该函数。

编辑:要备份其他人在这里说的话,我不会在这个例子中使用Thread.Sleep()。

答案 1 :(得分:1)

您希望通过使用Update阻止Coroutine循环来执行此操作(以及所有似乎不会使游戏生效的等待函数&#34;冻结&#34;)。

以下是您可能正在寻找的样本。

void OnMouseUp() 
{
    animator.SetBool("callAnim", false);
    animator.SetBool("callGoAway", true);

    //Removed the assignement of Time.deltaTime as it did nothing for you...

    StartCoroutine(DelayedCoroutine());
}

IEnumerator DoSomethingAfterDelay()
{
    yield return new WaitForSeconds(1f); // The parameter is the number of seconds to wait
    target.SendMessage(message, SendMessageOptions.RequireReceiver);
}

根据您的示例,很难确定您想要完成的内容,但上面的示例是&#34;正确的&#34;在Unity 3D中延迟后做某事的方法。如果您想延迟动画,只需将调用代码放在Coroutine中,就像我进行SendMessage调用一样。

协程是在它自己的特殊游戏循环上启动的,它与游戏的Update循环有点同时发生。这些对于许多不同的东西非常有用,并且提供了一种类型的&#34;线程&#34; (虽然不是真正的线程)。

注意
不要在Unity中使用Thread.Sleep(),它会直接冻结游戏循环,如果在糟糕的时间完成,可能会导致崩溃。 Unity游戏在一个线程上运行,该线程处理所有生命周期事件(Awake()Start()Update()等...)。调用Thread.Sleep()将停止执行这些事件,直到它返回并且很可能不是您正在寻找的内容,因为它会显示游戏已冻结并导致糟糕的用户体验。