Textスクリプトを実行するとNullReferenceException: Object reference not set to an instance of an objectと出る

実現したいこと

unityにて、textを画面上に表示し、そのtextでカウントダウンしたいのですが、 スクリプトを入れ、実行したところ
Object reference not set to an instance of an objectと出てうまくいきません、そのスクリプトはネット上にあったものを使いました。

発生している問題・エラーメッセージ

エラーメッセージ NullReferenceException: Object reference not set to an instance of an object CountDown.Update () (at Assets/CountDown.cs:45) ### 該当のソースコード ```ここに言語名を入力 C# ソースコード

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

public class CountDown : MonoBehaviour
{

// トータル制限時間 private float totalTime; // 制限時間(分) [SerializeField] private int minute; // 制限時間(秒) [SerializeField] private float seconds; // 前回Update時の秒数 private float oldSeconds; private Text timerText; void Start() { totalTime = minute * 60 + seconds; oldSeconds = 0f; timerText = GetComponentInChildren<Text>(); } void Update() { // 制限時間が0秒以下なら何もしない if (totalTime <= 0f) { return; } // 一旦トータルの制限時間を計測; totalTime = minute * 60 + seconds; totalTime -= Time.deltaTime; // 再設定 minute = (int)totalTime / 60; seconds = totalTime - minute * 60; // タイマー表示用UIテキストに時間を表示する if ((int)seconds != (int)oldSeconds) { timerText.text = minute.ToString("00") + ":" + ((int)seconds).ToString("00"); } oldSeconds = seconds; // 制限時間以下になったらコンソールに『制限時間終了』という文字列を表示する if (totalTime <= 0f) { Debug.Log("制限時間終了"); } }

}

試したこと

45行目のコメントアウト→エラーはなくなったが動作もしなかった。
minuteとsecondsを初期化→エラーはそのままだった。

補足情報(FW/ツールのバージョンなど)

Unity 2022.3.11f1を使用しています。

コメントを投稿

0 コメント