So I’m making a game and what I’d like to do is as follows: If you’ve collected all the items, you are being forwarded to an end screen, in which your total score is shown. However there is a problem. Since the variable score (which is used to keep track of the score) is part of an object in my game scene, I can’t acces the score variable in my end_screen scene.
Player Object code:
enter code hereusing UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PacMan_Controller : MonoBehaviour {
public float speed;
public float gravity = 20.0f;
public bool play = false;
public int score;
private Vector3 moveDirection = Vector3.zero;
private int count;
private int totalPickupCount;
public Text scoreText;
// Use this for initialization
void Start ()
{
DontDestroyOnLoad (transform.gameObject);
count = 0;
score = 0;
totalPickupCount = GameObject.FindGameObjectsWithTag ("PickUp").Length;
GetComponent<MeshRenderer> ().enabled = false;
}
// Update is called once per frame
void FixedUpdate ()
{
if (play)
{
float moveH = Input.GetAxis ("Horizontal");
float moveV = Input.GetAxis ("Vertical");
//Vector3 movement = new Vector3 (moveH, 0.0f, moveV);
//rigidbody.AddForce (movement * speed * Time.deltaTime);
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
//transform.Rotate(0, moveH, 0);
moveDirection = new Vector3(moveH, 0, moveV);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move (moveDirection * Time.deltaTime);
}
}
void OnTriggerEnter(Collider other)
{
if (play)
{
if (other.gameObject.tag == "PickUp")
{
other.gameObject.SetActive(false);
count = count + 1;
score = score + 10;
scoreText.text = "Score: " + score;
if (count >= totalPickupCount)
{
play = false;
Application.LoadLevel("Score");
}
}
}
}
}
My End_screen code (Which i’m trying to make it work):
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class End_Screen : MonoBehaviour {
public Text endText;
// Use this for initialization
void Start ()
{
endText.gameObject.SetActive (true);
int total = GameObject.Find("PacMan").GetComponent<PacMan_Controller>().score;
endText.text = "Total Score: " + total;
}
// Update is called once per frame
void Update () {
}
}
I’ve tried the DontDestroyOnLoad() function, but I prefer not to do this. Also, it doesn’t even work with this function ![]()
The error message I receive is: “NullReferenceException: Object reference not set to an instance of an object”.
I hope you can help me with this!