I recently made a game called Blocky in Unity and it had a distance scoring feature. I have found a bug where when you fall off the edge and hit the side of the platform the score says NaN and the scene disappears completely. It’s not urgent but I’d like it to be fixed. I have a screenshot and I can show you the code.
You need to post some of your relevant code or something. Are there any errors in the console? NaN is a special value that some float calculations can produce if you, for example, try to divide by 0.
My DistanceScore script is using UnityEngine; using UnityEngine.UI; public class Score : MonoBehaviour { public Transform player; public Text distanceText; // Update is called once per frame void Update () { distanceText.text = player.position.z.ToString("0"); } }
and this is my GameManager code using UnityEngine; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { bool gameHasEnded = false; public float restartDelay = 1f; public GameObject completeLevelUI; public void CompleteLevel() { completeLevelUI.SetActive(true); } public void EndGame () { if (gameHasEnded == false) { gameHasEnded = true; Debug.Log("GAME OVER"); Invoke("Restart", restartDelay); } } void Restart() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } }
Seems to me like you might of destroyed the player thus there is no reference to to the player so the function gives you back "NaN"
Have you got any script attached to player.I agree with TheRaider.It might be that you destroy player's object before you get score
Movement Script: using UnityEngine; public class PlayerMovement : MonoBehaviour { public Rigidbody rb; public float forwardForce = 2000f; public float sideForce = 500f; // Update is called once per frame void FixedUpdate() { // A forward force rb.AddForce(0, 0, forwardForce * Time.deltaTime); if (Input.GetKey("d")) { // Only executed if condition is met rb.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange); } if (Input.GetKey("a")) { // Only executed if condition is met rb.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange); } if (rb.position.y < -1f) { FindObjectOfType<GameManager>().EndGame(); } } }
Player Collision: public class PlayerCollision : MonoBehaviour { public PlayerMovement movement; void OnCollisionEnter (Collision collisionInfo) { if (collisionInfo.collider.tag == "Obstacle") { movement.enabled = false; FindObjectOfType<GameManager>().EndGame(); } } }
To me, it looks like gamemanager script issue.Try to remove CompleteLevel method and move your UI activation to EndGame,and see if that works. And it would be nice if you could use code tags for better reading