【问题标题】:How to change variable for a certain period of time如何在一段时间内更改变量
【发布时间】:2015-04-22 05:17:52
【问题描述】:

如何在 Unity3D 中更改变量仅 5 秒或直到某个事件?例如,改变速度:

void Start ()
{
    GetComponent<Rigidbody2D> ().velocity = Vector3.zero;
}

void Update ()
{
   if (Input.GetKey(KeyCode.W))
   {
       goUp ();
   }
}
public void goUp() {
   GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, 10);
}

自从按下 A 后,物体就一直上升。如何使对象不是一直上升,而是在按下 A 时的每一帧?而当 A 没有被按下时,物体的速度会回到零。我以前是这样弄的:

void Start () {
   GetComponent<Rigidbody2D> ().velocity = Vector3.zero;
}

void Update () {

   GetComponent<Rigidbody2D> ().velocity = Vector3.zero;

   if (Input.GetKey(KeyCode.A)) {
       goUp ();
   }

}

public void goUp() {
   GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, 10);
}

但是这种方法不合理,CPU过载。另外,我不能使用 Input.GetKeyUp(KeyCode.A) 或“else”语句作为触发器。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    看看 Unity/C# 中的 CoRoutines: http://docs.unity3d.com/Manual/Coroutines.html

    这可能完全符合您的需要。如果我正确理解您的问题,我会在下面放置一些伪代码。

    if (Input.GetKeyDown("a")) {
        goUp();
        StartCoroutine("ReduceSpeedAfter5Seconds");
    }
    
    IEnumerator ReduceSpeedAfter5Seconds() {
    GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, 10);
            yield return new WaitForSeconds(5.0f);
    }
    

    【讨论】:

    • 是的,它帮助了我。谢谢!
    【解决方案2】:

    我会使用 x 作为属性,就像它是速度一样。我只会伪编码它.. 在每个帧的 Update() 上,在这种情况下,您只关心 Speed,因此您只需调用它即可。您不必经常检查其他值,因为这些值应该由其他事件处理。

    Property Speed get;set;
    
        Void APressed()
    {
         Speed = 5;
    }
    
    Void AReleased()
    {
         Speed = 0;
    }
    

    对不起,我在 5 秒后忘记了第二部分.. 你可以添加这样的东西,如果 Unity 支持 async 关键字..然后你会更新你的 A press 看起来像这样

       Void APressed()
        {
             Speed = 5;
    ReduceSpeedAfter5Seconds();
        }
    
    
    public async Task ReduceSpeedAfter5Seconds()
    {
        await Task.Delay(5000);
        Speed = 0;
    }
    

    【讨论】:

    • 请注意,Unity 并不总是能很好地与传统的 C# 线程选项配合使用(请参阅 here)。我什至不确定他们使用的 Mono 运行时是否支持 Task 类。
    【解决方案3】:

    你试过了吗?

    if (Input.GetKey(KeyCode.A)) {
           goUp ();
       }
    else
    {
        GetComponent<Rigidbody2D> ().velocity = Vector3.zero;
    }
    

    【讨论】:

    • 是的。它正在调用“GetComponent ().velocity = Vector3.zero;”每一帧都会导致 CPU 过载。
    • 那么你可以试试这个 // if (Input.GetKey(KeyCode.A)) { goUp (); } else if(Input.GetKeyUp(KeyCode.A)) { GetComponent ().velocity = Vector3.zero; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多