2017-07-11 16 views
0

私のゲームでは、敵があります。この敵がPlayerにminimalDistanceにいる場合、タイマーが開始されます。これは正常に動作しますが、UIにタイマーを表示する方法はわかりません。私はこのスクリプトを試してみましたが、インスペクタのテキストを添付しました:開始タイマー距離Unity3D

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); 
     } 
    } 
} 

しかし、テキストがまだ表示され、「新しいテキスト」で、ゲーム全体を表示します。

答えて

1

ゲームオブジェクトにはTextコンポーネントのあるものはほかにありませんが、代わりにGameObject.SetActive(bool active)を使用することもできますが、おそらく問題は解決しません。

おそらく、TimerTextへの参照がありません。

+0

あなたはそうです!私は間違ったTextオブジェクト(私には恥)を入れましたが、もう一つの問題があります。敵が殺された場合、そのスクリプトは破壊されますが、テキストはまだキャンバスに残ります。その時点で、テキストは不可視でなければなりません。どうすれば別のスクリプトからTextelementにアクセスできますか? –

+1

また、敵が['OnDestroy'](https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnDestroy.html)を使ってEnemyFollowコンポーネントから破壊され、テキストを無効にする/隠す/削除するとイベントを得ることができますオブジェクト/コンポーネント。 エレミを完全に削除したくない場合は、['OnDisable'](https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnDisable.html)を使用することもできます – MrDos

+0

うわー、OnDisableについて知りませんでした。それは完全に働いた!どうもありがとう :) –