- Home /
problem with MissingReferenceException
hello, i have this script public class scoremeter : MonoBehaviour { public Transform player; public Text scoretext; public Text record; void Update () { scoretext.text = player.position.y.ToString("0"); record.text = "top:" + ((int)PlayerPrefs.GetFloat ("record")).ToString(); if (PlayerPrefs.GetFloat("record") < player.position.y) { PlayerPrefs.SetFloat ("record", player.position.y); } } }
and then if my player is null the console writes : MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. i tried to check if my player is null by this if (player != null)
but is still writing this. my game is 2d please tell me how to fix it sorry for bad english thanks
Answer by bpaynom · Aug 29, 2018 at 01:29 PM
Try something like this
using UnityEngine;
using UnityEngine.UI;
public class scoremeter : MonoBehaviour
{
public Transform player;
public Text scoretext;
public Text record;
void Update()
{
if ( player == null || scoretext == null || record == null)
return;
scoretext.text = player.position.y.ToString( "0" );
record.text = "top:" + ((int)PlayerPrefs.GetFloat( "record" )).ToString();
if ( PlayerPrefs.GetFloat( "record" ) < player.position.y )
{
PlayerPrefs.SetFloat( "record" , player.position.y );
}
}
}
Your answer
Follow this Question
Related Questions
How to put Streamwriter into an array? 1 Answer
Best practice handling deleted object refences during SceneManager.LoadScene 0 Answers
Sorting Error 0 Answers
Destroyed Object Error 2 Answers