New to unity/coding working on my first game project. How can I add a highscore to my current gameplayer script? I want to save a highscore that will remain when the scene ends via collision until a new score is achieved.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour {
// Movement speed
public float speed = 2;
public Text countText;
public AudioClip power_1_d;
private int score;
// force
public float force = 300;
// Use this for initialization
void Start () {
// Fly towards the right
GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
score = 0;
SetCountText ();
}
// Update is called once per frame
void Update () {
//
if (Input.GetKeyDown(KeyCode.Space))
GetComponent<Rigidbody2D>().AddForce(Vector2.up * force);
}
void OnCollisionEnter2D(Collision2D coll) {
// Restart
SceneManager.LoadScene(Application.loadedLevel);
}
//OnTriggerEnter2D is called whenever this object overlaps with a trigger collider.
void OnTriggerEnter2D(Collider2D other)
{
//Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
if (other.gameObject.CompareTag ("PickUp")) {
other.gameObject.SetActive (false);
score = score + 1;
SetCountText ();
SoundManager2.instance.RandomizeSfx (power_1_d);
}
}
void SetCountText()
{
countText.text = "Score: " + score.ToString ();
}
}
@ShadyProductions Thank you for your response. I am still a little lost. I forgot to mention if you didnt see from my previous script, my player is picking up gameobject (coins) and this is where my score is coming from.
In the script you posted above you mentioned there is no need to attach it to a game object. Why would this not be the case since my current “Score/CountText” is currently attached to script being used on my player which allows him to fly (see screenshot) ?
Just trying to figure this out, like I said I am completely brand new to all of this, unity as well as coding. I have been following some of the tutorials on unity. In regards to my original score script I was following the script used in the unity roll a ball tutorial.
Should I be starting brand new in regards to score as well? Sorry for all of the questions, any direction would be helpful. I appreciate all of your help thus far.