要求停止后,Unity time.deltatime中的错误仍然运行

时间:2018-11-29 12:47:08

标签: c# unity3d

问题出在时间delta.time函数上。即使在Left变量的值越过0之后,它仍会运行。我是编码的绝对新手,请帮助我。

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;

    public class PlayerController : MonoBehaviour
    {
        private Rigidbody rb;

        public float speed = 1;
        private int count;

        //Text UI variables
        public Text countText;
        public Text winText;
        public Text Timer;
        private bool outOfTime = false;


        public float totalTime = 15.00f;
        private float timeLeft;

        void Start()
        {
            rb = GetComponent<Rigidbody>();
            count = 0;
            SetTextUpdate();
            winText.text = "";
            timeLeft = totalTime;
            // time left was declared as total time
        }

        void Update()
        {


        }

        void FixedUpdate()
        {
            if (timeLeft < 0)
            {
                winText.text = "Oops, you lost";
                outOfTime = true;
            }
            else
            {
                timeLeft = timeLeft - Time.deltaTime;
            }
            // the time left still continues to reduce even after reaching 0.
            Timer.text = timeLeft.ToString();

            float movementHorizontal = Input.GetAxis("Horizontal");
            float movementVertical = Input.GetAxis("Vertical");

            Vector3 movement = new Vector3(movementHorizontal, 0.0f, movementVertical);
            rb.AddForce(movement * speed);
            timeLeft -= Time.deltaTime;
        }

        void OnTriggerEnter(Collider other)
        {
            if (other.gameObject.CompareTag("Pick Up"))
            {
                other.gameObject.SetActive(false);
                count = count + 1;
                SetTextUpdate();

            }
        }
        void SetTextUpdate()
        {
            countText.text = "Count: " + count.ToString();
            if (count == 10 && outOfTime == false)
            {
                winText.text = ("You win");
            }

        }
    }

我是编码的新手,因此希望尽快获得帮助。这只是一个简单的“滚球”游戏,我尝试根据给定的经验进行修改。

1 个答案:

答案 0 :(得分:0)

FixedUpdate中,即使时间用完,您仍在继续减少时间并更新显示。试试这个:

void FixedUpdate()
{
    if (timeLeft < 0)
    {
        Timer.text = timeLeft.ToString();
        winText.text = "Oops, you lost";
        outOfTime = true;
    }
    else
    {
        timeLeft = timeLeft - Time.deltaTime;
        Timer.text = timeLeft.ToString();
    }

    // assume you want physics to continue after time is up
    float movementHorizontal = Input.GetAxis("Horizontal");
    float movementVertical = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(movementHorizontal, 0.0f, movementVertical);
    rb.AddForce(movement * speed);

    // don't need this line timeLeft -= Time.deltaTime;
}