【问题标题】:How to wait some seconds before doing something in OnMouseUp Event如何在 OnMouseUp 事件中做某事之前等待几秒钟
【发布时间】:2014-10-28 23:41:20
【问题描述】:

我正在编写带有一些动画的游戏,并在用户单击按钮时使用这些动画。我想向用户展示动画,而不是“只是”用 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);
        }
    }
}

【问题讨论】:

  • Thread.Sleep(1000) 将等待一秒钟,您是否正在寻找类似的东西?
  • 您尝试等待一段时间的代码在哪里?
  • 正如我所写的,我尝试将 inGameTime += Time.deltaTime 放入 onMouseUp() 方法,但它没有按预期工作,因为 OnMouseUp 方法只返回一个最小的 deltaTime跨度>
  • 您不想在处理用户输入时等待。如果您希望动画延迟,那么为什么不使用启动时什么都不做(对于某些帧数)的动画?

标签: c# unity3d


【解决方案1】:

我不完全确定您尝试在 onMouseUp 中使用 Time.deltaTime 做什么。这只是自最后一帧渲染以来的时间(以秒为单位),并且无论您尝试在何处访问它都应该表现相同。通常它用于每帧调用的函数中,而不是像 onMouseUp 这样的一次性事件。

尽管不确定您要达到什么目标,但听起来您应该使用 Invoke:

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

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

编辑:为了备份其他人在这里所说的内容,我不会在这种情况下使用 Thread.Sleep()。

【讨论】:

    【解决方案2】:

    您想通过使用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 延迟后做某事的“正确”方式。如果您想延迟动画,只需将调用代码放在 Coroutine 中,就像我调用 SendMessage 一样。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-14
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多