C#Unity中如何让一个方法在一段时间内有效

How to make a method work in a period of time in C# Unity

我已经为我的这段代码苦苦挣扎了一段时间。 我为我的播放器提供了一种方法,当它收集到一定数量的收藏品时,它会变得更快。但我希望我的播放器在一定时间内走得更快(例如 3 秒)。并且(收藏品的)计数器必须归零,所以当玩家再次收集到一定数量的收藏品时,它再次变得更快,等等。

我有一个 class 用于我的所有 PowerUp 和一个不同的 class:继承自 PowerUp 的 Speder。 当它收集到一定数量的收藏品时,速度变量上升在我的玩家脚本中:Player0.

通电

using UnityEngine;
using System.Collections;

public class PowerUp : MonoBehaviour
{
  public static int counter = 0;

  void OnTriggerEnter2D(Collider2D other)
  {
    if (other.tag == "Player")
    {
      Speder.BoostThaSpeed();
      Destroy(this.gameObject);
      counter++;

      if (counter == 3)
      {
        counter = 0;
      }
    }
  } 
}

斯佩德

using UnityEngine;
using System.Collections;

public class Speder : PowerUp
{
  public static void BoostThaSpeed()
  {
    if (counter == 2)
    {
      Player0.speed = Player0.speed * 2;
    }

    else if (counter < 2)
    {
      Player0.speed = Player0.speed = 3.5f;
    }
  }
  void OnGUI()
  {
    GUI.Box(new Rect(750, 0, 130, 20), "Counter:" + counter);
  }
}

玩家 0

using UnityEngine;
using System.Collections;

public class Player0 : MonoBehaviour
{

  // SPEEDVARIABLES
  public static float speed = 3.5f;

void Update()
  {
 // MOVING CODE

    if (Input.GetKey(KeyCode.LeftArrow))
    {
      rigidbody2D.velocity = new Vector2(-speed, rigidbody2D.velocity.y);   // - speedForce (om naar links te gaan)
      transform.localScale = new Vector3(-0.3f, 0.3f, 0.3f);   
    }

    else if (Input.GetKey(KeyCode.RightArrow))
    {
      rigidbody2D.velocity = new Vector2(speed, rigidbody2D.velocity.y);   // + speedforce (om naar rechts te gaan)
      transform.localScale = new Vector3(0.3f, 0.3f, 0.3f);
    }

    else
    {
     rigidbody2D.velocity = new Vector2(0, rigidbody2D.velocity.y);
    }
}

您可以在更新方法中使用 Time.deltaTime 来减少变量

向 Speder 添加一个 SpeedboostTimeRemaining 属性 并将其设置为任何时间,比如在 BoostThaSpeed 方法中设置为 10

然后给Speder添加一个update方法并放入

if(SpeedboostTimeRemaining > 0)
{
    SpeedboostTimeRemaining -= Time.deltaTime
    if(SpeedboostTimeRemaining < 0)
    {
        SpeedboostTimeRemaining = 0;
        Player0.speed = 3.5f;
    }
}