How to access variables in another scene?
How can I access variables in another scene? Let say I have 2 scenes, scene1 and scene2. In Scene2, I have a GameObject called "TypeBox" with "boxo" tag. I attached the script below (called "TypeChecker.cs") into "TypeBox". Meanwhile in scene1, I have a GameObject called "enemy1" and attached the script below (called "SpawnCheck.cs") into it. I want to transfer the boolean variable win and lose from scene2 (TypeChecker) into scene1 (SpawnCheck).
The unity keeps showing errors: NullReferenceException: Object reference not set to an instance of an object SpawnCheck.Start () (at Assets/SpawnCheck.cs:18)
How can I fix that? Thank you..
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TypeChecker : MonoBehaviour {
private static string[] kamus = new string[] {"dosen","mandi","kuliah","sakit","absen","tidur","pingsan","belajar","tugas","lambat","alasan"};
private static string[] kamus2 = new string[] {"oesnd","dinam","iahluk","kitas","senab","ditur","nigspan","jaraleb","gutas","bmtaal","aaansl"};
private static int[] cek = new int[] {0,0,0,0,0,0,0,0,0,0};
public static int a;
private string type = kamus[a];
private string type2 = kamus2[a];
private string typeStr = string.Empty;
private int temp;
private int cekcek = 0;
private Rect windowRect = new Rect(0,0,Screen.width, Screen.height);
public GUIStyle typestyle;
public GUIStyle typestyle2;
public GUIStyle typestyle3;
public GUIStyle typestyle4;
public GUIStyle typestyle5;
public GUIStyle typestyle6;
public GameObject enemy2;
public GameObject chara;
public int startingHealth = 100; // The amount of health the player starts the game with.
public int currentHealth;
public int currentHealthEnemy; // The current health the player has.
public Slider healthSlider;
public Slider healthSliderEnemy; // Reference to the UI's health bar. // Reference to an image to flash on the screen on being hurt.
public AudioClip deathClip;
public AudioClip deathClipEnemy;
public AudioClip enemyhurt;
public AudioClip playerhurt;
public Image damageImage;
public float flashSpeed = 5f; // The speed the damageImage will fade at.
public Color flashColour = new Color(1f, 0f, 0f, 0.1f);
public Color flashColour2 = new Color(1f, 0f, 0f, 0.1f);
Animator anim; // Reference to the Animator component.
AudioSource playerAudio;
// AudioSource playerAudio2;
bool isDead = false;
bool enemyisDead = false; // Whether the player is dead.
bool damaged;
bool enemydamaged;
public bool CanPause;
public bool win;
public bool lose;
// Use this for initialization
void Awake () {
// Setting up the references.
DontDestroyOnLoad(this);
a = Random.Range(0,9);
CanPause = true;
win = false;
lose = false;
anim = GetComponent <Animator> ();
playerAudio = GetComponent <AudioSource> ();
// playerAudio2 = GetComponent <AudioSource> ();
// playerMovement = GetComponent <PlayerMovement> ();
// playerShooting = GetComponentInChildren <PlayerShooting> ();
// Set the initial health of the player.
currentHealth = startingHealth;
currentHealthEnemy = startingHealth;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.Escape)) {
if(CanPause)
{
Debug.Log("pause");
Time.timeScale=0;
CanPause = false;
}
else
{
Time.timeScale=1;
CanPause=true;
}
}
// If the player has just been damaged...
if(damaged)
{
// ... set the colour of the damageImage to the flash colour.
damageImage.color = flashColour;
}
// Otherwise...
else if(enemydamaged){
damageImage.color = flashColour2;
}
else
{
// ... transition the colour back to clear.
damageImage.color = Color.Lerp (damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
}
// Reset the damaged flag.
damaged = false;
enemydamaged = false;
}
void OnGUI(){
GUI.Window (0, windowRect, WindowFunction, "", typestyle2);
GUI.Label(new Rect(7*Screen.width/16, 50, 100, 20), type2, typestyle4);
if (isDead == true) {
GUI.Label (new Rect (7 * Screen.width / 16, Screen.height/2, 100, 20), "You Lose", typestyle6);
lose = true;
win = false;
Application.LoadLevel(3);
} else if (enemyisDead == true) {
GUI.Label(new Rect(7*Screen.width/16, Screen.height/2, 100, 20), "You Win", typestyle6);
win = true;
lose = false;
Application.LoadLevel(3);
}
}
void WindowFunction(int windowID){
// GUI.SetNextControlName("MyTextField");
typeStr = GUI.TextField(new Rect(Screen.width/4, Screen.height/5 , 7*Screen.width/16 , Screen.height/14), typeStr, 15, typestyle);
if (GUI.Button (new Rect (11*Screen.width/16, Screen.height/5, Screen.width/15, Screen.height/14), "", typestyle3))
// GUI.FocusControl("MyTextField")
{
if(typeStr == type){
iTween.PunchPosition(chara, iTween.Hash("z", 22, "easeType", "easeInOutExpo", "looptype", "none", "delay", 0));
iTween.PunchPosition(enemy2, iTween.Hash("z", -3, "easeType", "easeInOutExpo", "looptype", "none", "delay", 0));
TakeDamageEnemy(20);
typeStr = "";
cek[a]=1;
temp=a;
a = Random.Range(0,9);
type = kamus[a];
type2 = kamus2[a];
while(a==temp || cek[a]==1){
a = Random.Range(0,9);
type = kamus[a];
type2 = kamus2[a];
}
} else{
iTween.PunchPosition(enemy2, iTween.Hash("z", 22, "easeType", "easeInOutExpo", "looptype", "none", "delay", 0));
iTween.PunchPosition(chara, iTween.Hash("z", -3, "easeType", "easeInOutExpo", "looptype", "none", "delay", 0));
cekcek = 1;
if(cekcek == 1){
// iTween.MoveBy(enemy2, iTween.Hash("z", -22, "easeType", "easeInOutExpo", "looptype", "none", "delay", .1));
cekcek = 0;
}
TakeDamage(20);
typeStr = "";
cek[a]=1;
temp=a;
a = Random.Range(0,9);
type = kamus[a];
type2 = kamus2[a];
while(a==temp || cek[a]==1){
a = Random.Range(0,9);
type = kamus[a];
type2 = kamus2[a];
}
}
}
GUI.Label (new Rect (7*Screen.width / 18, 11 * Screen.height / 100, Screen.width / 5, Screen.height / 8), "RULE : Arrange the scrambled words above and click enter (click not press)", typestyle5);
}
public void TakeDamage (int amount)
{
// Set the damaged flag so the screen will flash.
damaged = true;
// Reduce the current health by the damage amount.
currentHealth -= amount;
// Set the health bar's value to the current health.
healthSlider.value = currentHealth;
// Play the hurt sound effect.
playerAudio.Play ();
// If the player has lost all it's health and the death flag hasn't been set yet...
if(currentHealth <= 0 && isDead == false && enemyisDead == false)
{
// ... it should die.
Death ();
}
}
public void TakeDamageEnemy (int amount)
{
// Set the damaged flag so the screen will flash.
enemydamaged = true;
// Reduce the current health by the damage amount.
currentHealthEnemy -= amount;
// Set the health bar's value to the current health.
healthSliderEnemy.value = currentHealthEnemy;
// Play the hurt sound effect.
// playerAudio.clip = enemyhurt;
// playerAudio.Play ();
// playerAudio.clip = playerhurt;
// If the player has lost all it's health and the death flag hasn't been set yet...
if(currentHealthEnemy <= 0 && isDead == false && enemyisDead == false)
{
// ... it should die.
EnemyDeath ();
}
}
void Death ()
{
// Set the death flag so this function won't be called again.
isDead = true;
// Turn off any remaining shooting effects.
// playerShooting.DisableEffects ();
// Tell the animator that the player is dead.
//anim.SetTrigger ("Die");
// Set the audiosource to play the death clip and play it (this will stop the hurt sound from playing).
playerAudio.clip = deathClip;
playerAudio.Play ();
iTween.RotateBy(chara, iTween.Hash("x", -.25, "easeType", "easeInOutBack", "loopType", "once", "delay", .2));
// Turn off the movement and shooting scripts.
// playerMovement.enabled = false;
// playerShooting.enabled = false;
}
void EnemyDeath ()
{
// Set the death flag so this function won't be called again.
enemyisDead = true;
// Turn off any remaining shooting effects.
// playerShooting.DisableEffects ();
// Tell the animator that the player is dead.
//anim.SetTrigger ("Die");
// Set the audiosource to play the death clip and play it (this will stop the hurt sound from playing).
playerAudio.clip = deathClipEnemy;
playerAudio.Play ();
iTween.RotateBy(enemy2, iTween.Hash("x", .5, "easeType", "easeInOutBack", "loopType", "once", "delay", .2));
// Turn off the movement and shooting scripts.
// playerMovement.enabled = false;
// playerShooting.enabled = false;
}
}
====================================================================================
using UnityEngine;
using System.Collections;
public class SpawnCheck : MonoBehaviour {
public bool a;
public bool b;
public GameObject hero;
// public GameObject enem;
public Transform SpawnPoint;
public Transform SpawnPoint2;
public TypeChecker typeChecker;
public GameObject enemy;
// Use this for initialization
void Start () {
// GameObject typebox = GameObject.Find("TypeBox");
typeChecker = GameObject.FindWithTag("boxo").GetComponent<TypeChecker>();
a = typeChecker.win;
b = typeChecker.lose;
}
// Update is called once per frame
void Update () {
if (a == true && b == false) {
Destroy (enemy);
hero.transform.position = SpawnPoint.position;
} else if (b == true && a == false) {
hero.transform.position = SpawnPoint2.position;
}
}
}
This has been asked several times before. Search "unity other scene" and you'll find lots of Answers (including the one below.) One of the questions is exactly what you asked, but Q's about gameObjects in other scenes, etc... also have useful info.
Answer by Maenor · Oct 17, 2015 at 08:27 PM
Not related but ... That Script seems to be a mess xP Why didn't you used different scripts instead? xO
Answer by PictonicStudio · Oct 17, 2015 at 08:06 PM
Have you tried a SIngleton, and DontDestroyOnLoad? You could also store the variable in playerprefs.
Your answer
Follow this Question
Related Questions
Why is my scene not loading? 2 Answers
Access To a Variable of another script which in another scene 0 Answers
List is not refreshing after LoadingScene 1 Answer
Create new scene deleted my scene 0 Answers