简体   繁体   English

在距离Unity3D上启动计时器

[英]Start Timer on Distance Unity3D

In my game, there's an enemy. 在我的游戏中,有一个敌人。 If this enemy is at a minimalDistance to the Player, a timer should start. 如果此敌人与玩家的minimalDistance ,则应启动计时器。 This works fine, but I don't know how to show the Timer on the UI. 这可以正常工作,但是我不知道如何在UI上显示Timer。 I've tried this Script and attached a Text in the Inspector: 我已经尝试过此脚本,并在检查器中附加了一个文本:

using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class EnemyFollow : MonoBehaviour
{
    public Text TimerText;
    public Transform target;
    public Transform myTransform;
    private const float minDistance = 5f;
    float TimeLeft = 10.0f;
    public float lockedY = 1f;
    [SerializeField] private string loadlevel;

    void Start()
    {
        TimerText.enabled = false;

        Vector3 tmp = transform.position;
        tmp.y = lockedY;
        transform.position = tmp;
    }

    // Update is called once per frame
    void Update()
    {
        //Enemy follows the player
        transform.LookAt(target);
        transform.Translate(Vector3.forward * 7 * Time.deltaTime);

        //If enemy is at minDistance, a Timer starts
        if ((myTransform.transform.position - target.transform.position).sqrMagnitude <= minDistance * minDistance)
        {
            TimeLeft -= Time.deltaTime;
            TimerText.enabled = true;
            TimerText.text = "Drone sends Signal:" + Mathf.Round(Zeit);
        }

        //If the Countdown is done, the game is over
        if (Zeit < 0)
        {
            SceneManager.LoadScene(loadlevel);
        }
    }
}

But the Text Shows up the whole game, still with "new text" displaying. 但是文字显示了整个游戏,仍然显示“新文字”。

There's probably nothing else on the game object with the Text component, you might want to use GameObject.SetActive(bool active) instead but this probably won't fix your issue. 带有Text组件的游戏对象上可能没有其他东西,您可能想使用GameObject.SetActive(bool active)但这可能无法解决您的问题。

I can't help but think about a reference problem in the editor, missing a reference to your TimerText probably. 我不禁想到编辑器中的引用问题,可能缺少对TimerText的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM