【问题标题】:How to call a function when "user action" ends?“用户操作”结束时如何调用函数?
【发布时间】:2019-07-03 18:42:05
【问题描述】:

我正在使用 C# 和 Unity 开发一个多媒体应用程序。

在这个应用程序中,用户可以使用鼠标滚轮移动对象;所以我写了

private void MoveObjectUpDown(float value)
{
     MyObject.transform.position = MyObject.transform.position + new Vector3(0, value, 0); 
     StartCoroutine(UpdateObjectPositionToServer(MyObject.transform.position, MyObject.MyObjectID);            

}

MyObjectUpAndDown 在更新检查中被调用

Input.GetAxis("鼠标滚轮");

UpdateObjectPositionToServer 是对 Web 服务的调用;在这个网络服务中,我通过查询更新了一个 MySql 表。

你可以想象,如果用户移动鼠标来移动我的对象,将会有很多对 UpdateObjectPositionToServer 的调用;我的问题是:

我可以使用哪种方法在每次用户移动后不调用 UpdateObjectPositionToServer,而只在用户移动结束时调用一次(可能 1 或 2 秒用户不移动该对象)?

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    解决此问题的一种方法是创建一个包装协程,该协程在启动 UpdateObjectPositionToServer 协程之前等待一段时间,并停止任何先前存在的包装协程实例。

    private IEnumerator currentWaitCoroutine = null;
    
    private void MoveObjectUpDown(float value)
    {
         MyObject.transform.position = MyObject.transform.position + new Vector3(0, value, 0); 
    
         if (currentWaitCoroutine != null)
         {
             StopCoroutine(currentWaitCoroutine);
         }
    
         currentWaitCoroutine = WaitAndCall(1.5f);
         StartCoroutine(currentWaitCoroutine);
    }
    
    private IEnumerator WaitAndCall(float seconds) {
        yield return new WaitForSeconds(seconds);
    
        StartCoroutine(UpdateObjectPositionToServer(MyObject.transform.position, MyObject.MyObjectID);   
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-16
      • 2012-02-08
      • 2013-09-12
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 2020-11-24
      • 2013-12-24
      相关资源
      最近更新 更多