Hey guys,
so I want to store the current score of my Pong game with PlayerPrefs so that I can load the scene (after a goal) again and display the score. But somehow it just gives my 0:0 everytime someone makes a goal. Maybe someone can help me.
Ball Script (OnCollisionEnter2D is important)
using UnityEngine;
public class Ball : MonoBehaviour {
public float startSpeed;
public float collisionSpeedMultiplier;
public GameManager gm;
private Rigidbody2D rb;
void Awake ()
{
gm = Camera.main.GetComponent<GameManager> ();
rb = GetComponent<Rigidbody2D> ();
float angle = Random.Range (120f, 240f) + Random.Range (0f, 2f) * 180f;
float radAngle = angle * Mathf.Deg2Rad;
Vector2 startDir = new Vector2 (Mathf.Cos (radAngle), Mathf.Sin (radAngle));
rb.velocity = startDir * startSpeed;
}
void OnCollisionEnter2D (Collision2D col)
{
rb.AddForce (rb.velocity.normalized * collisionSpeedMultiplier, ForceMode2D.Impulse);
if (col.gameObject.CompareTag ("TriggerRight")) {
PlayerPrefs.SetInt ("pointsP1", gm.pointsP1++);
gm.GoalPoint ();
} else if (col.gameObject.CompareTag ("TriggerLeft")) {
PlayerPrefs.SetInt ("pointsP2", gm.pointsP2++);
gm.GoalPoint ();
}
}
}
GameManager Script:
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
[SerializeField]
public int pointsP1;
[SerializeField]
public int pointsP2;
public Text score;
void Start ()
{
pointsP1 = PlayerPrefs.GetInt ("pointsP1");
pointsP2 = PlayerPrefs.GetInt ("pointsP2");
Debug.Log (pointsP1 + ":" + pointsP2);
score.text = pointsP1 + ":" + pointsP2;
}
public void GoalPoint ()
{
SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex);
}
}