- Home /
How to Use DontDestroyOnLoad on my C# Script?
Hey uhm, i do really need your help guys, I'm creating a shop script where the player can purchase a Power-Up( a coin-magnet to be specific), the situation is, the gameObjects are already placed on the terrain but they're not active. However, i have a shop scene and game scene. When the player purchase the power-up, then the gameObjects should become active and visible.
here is my code on the shop:
using UnityEngine; using System.Collections;
public class ConfirmScript : MonoBehaviour {
public bool isMagnetBought = false;
public void EnableMagnet(bool dec) {
if(dec == true){
isMagnetBought = true;
DontDestroyOnLoad(this);
Application.LoadLevel(6);
}
}
}
while this is the code in-game:
using UnityEngine; using System.Collections;
public class EnableMagnet : MonoBehaviour {
public ConfirmScript cs;
public GameObject magnet;
void Start() {
if(cs.isMagnetBought == true){
magnet.SetActive(true);
}
}
}
and i received this error:
NullReferenceException: Object reference not set to an instance of an object EnableMagnet.Start () (at Assets/Scripts/EnableMagnet.cs:10)
which means i have an error on this line:
if(cs.isMagnetBought == true)
what could be the problem? I appreciate any help you can give. Thanks!!!
Answer by ShadyProductions · Jan 22, 2016 at 08:15 PM
Did you initialized your ConfirmScript in your start method or the inspector? For example:
cs = GetComponent<ConfirmScript>();
Otherwise try changing the following:
DontDestroyOnLoad(gameObject);
thank you sir, i'll check it out right now. Will be back for a moment!!!
Your answer
Follow this Question
Related Questions
gameObject.SetActive (true); Not working 10 Answers
unity2D colliders not working properly,,Unity2D Colliders don't seem to be working HELP PLEASE! 0 Answers
How to respawn an object when collision happens with a different object? 1 Answer
Reenabling GameObject with SetActive - NullReferenceException 1 Answer
Activating a prefab in the scene by find it over a tag? 1 Answer