2014-10-28 69 views
0

我正在用一些动画编写游戏,并在用户单击按钮时使用这些动画。我想向用户展示动画,而不是“只”用Application.loadLevel调用新的关卡。我想我可以在onMouseUp方法中使用Time.DeltaTime并将其添加到预定义的0f值,然后检查它是否大于(例如)1f,但它不会工作,因为onMouseUp方法只会添加“它是自己的时间“作为德尔塔时间。如何等待几秒钟,然后在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); 
     } 
    } 
} 
+0

Thread.Sleep(1000)将等待一秒钟,你是否在寻找沿这些线的东西? – Bayeni 2014-10-28 13:33:47

+0

你试图等待一段时间的代码在哪里? – Reniuz 2014-10-28 13:36:09

+0

正如我写的,我试图把一个inGameTime + = Time.deltaTime放到onMouseUp()方法中,但它不能像预期的那样工作,因为OnMouseUp方法只返回最小的deltaTime – Zwiebel 2014-10-28 13:43:41

回答

1

我不是完全肯定你的努力在onMouseUp使用Time.deltaTime做。这只是自上一帧渲染以来的几秒钟内的时间,无论您尝试访问它的位置都应该保持不变。通常它被用在一个被称为每帧的函数中,而不是像onMouseUp这样的一次性事件。

尽管不是一定你想达到什么目的,这听起来像你应该使用调用:

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

只要把你想被推迟到一个单独的函数的代码,然后调用该功能在onMouseUp中延迟。

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

1

您希望通过使用Coroutine阻止Update循环来完成此操作(以及所有看起来不会使游戏“冻结”的等待函数)。

下面是您可能要查找的示例。

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); 
} 

根据你的榜样,很难确定究竟你想要什么来完成但上面的例子是“正确”的方式在Unity 3D的延迟之后做一些事情。如果您想延迟动画,只需将调用代码放入协同程序中,就像我调用SendMessage一样。

协程在它自己的特殊游戏循环中启动,与您游戏的Update循环有点并发。这些对于许多不同的事情非常有用,并提供了一种“线程化”(尽管不是真正的线程化)。

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

相关问题