So I am creating a 2D platformer and the goal is to go as long as possible without dying, and I need to make it so when the player hits the ground, the text displaying the amount of time the player has ran for restarts. I will post the code that I have already written.
Any and all help is greatly appreciated,
Thank you.
Score Manager Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour
{
public Text scoreText;
public Text hiScoreText;
public float scoreCount = 0;
public float hiScoreCount = 0;
public float pointsPerSecond = 2;
public bool scoreIncreasing;
void Update()
{
if (scoreIncreasing)
{
scoreCount += pointsPerSecond * Time.deltaTime;
}
if (scoreCount > hiScoreCount)
{
hiScoreCount = scoreCount;
}
scoreText.text = "Score: " + Mathf.Round(scoreCount);
hiScoreText.text = "High Score: " + Mathf.Round(hiScoreCount);
}
public void ResetPlayerScore()
{
scoreCount = 0;
scoreText.text = "Score: 0";
scoreIncreasing = false;
}
public void EnableScoring()
{
scoreIncreasing = true;
}
}
Caller code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Caller : MonoBehaviour {
ScoreManager _sm;
void Start()
{
// Get reference to ScoreManager in scene
_sm = GameObject.Find("ScoreManager").GetComponent<ScoreManager>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("Player"))
{
_sm.ResetPlayerScore(); // sample example of calling a method written in your ScoreManager
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("Player"))
{
_sm.EnableScoring();
}
}
}