Hello guys, first of all i want to say that i am a complete noob concerning unity programming therefore i would gladly appreciate your help.
So my problem is that i have a background music object in DontDestroyOnLoad so my audio file gets played seamlessly when switching scenes. I also have a toggle mute button in one scene which works exactly like it should when i start the game with this specific scene. But when i switch scenes and come back to that one specific scene i can't use my toggle mute button anymore and get the error: "The object of type AudioSource has been destroyed but you still try to access it".
I know the reason for this is that my backround music object is in dontdestroyonload.
How can i fix it?
Or how can i access this background music object which is in DontDestroyOnLoad?
Please help me i am kinda lost right now. :)
↧
Can't access an object which is in DontDestroyOnLoad
↧
Dont destroy on load is destroying my Game Manager
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public static GameManager Instance
{
get
{
if(_instance !=null)
{
return _instance;
}
else
{
GameObject gameManager = new GameObject("GameManager");
_instance = gameManager.AddComponent ();
return _instance;
}
}
}
private static GameManager _instance;
public string titlescreenname = "TitleScene";
[HideInInspector]
public int PreviousScore = 0;
public float pointsperunittravelled = 0.0f;
private static float highScore = 0.0f;
private bool hasSaved = false;
private float Score = 0.0f;
public float gamespeed = 10.0f;
private bool gameOver =false;
// Use this for initialization
void Start ()
{
if (_instance != this)
{
if (_instance == null)
{
_instance = this;
}
else
{
Destroy (gameObject);
}
}
LoadHighScore ();
DontDestroyOnLoad(gameObject);
}
// Update is called once per frame
void Update () {
if (SceneManager.GetActiveScene().name != titlescreenname) {
if (GameObject.FindGameObjectWithTag ("Player") == null) {
gameOver = true;
}
if (gameOver) {
if (!hasSaved)
{
SaveHighScore ();
PreviousScore = (int)Score;
hasSaved = true;
}
if (Input.anyKeyDown) {
SceneManager.LoadScene(titlescreenname);
}
}
if (!gameOver) {
Score += pointsperunittravelled * gamespeed * Time.deltaTime;
if (Score > highScore) {
highScore = Score;
}
}
}
else {
//Reset stuff for next game
ResetGame();
}
}
void ResetGame()
{
Score = 0.0f;
gameOver = false;
hasSaved = false;
}
void LoadHighScore()
{
highScore = PlayerPrefs.GetInt ("HighScore");
}
void SaveHighScore()
{
PlayerPrefs.SetInt ("HighScore", (int)highScore);
PlayerPrefs.Save ();
}
void OnGUI()
{
if(SceneManager.GetActiveScene().name != titlescreenname)
{
int currentscore = (int)Score;
int currenthighScore = (int)highScore;
GUILayout.Label ("Score: " + currentscore.ToString ());
GUILayout.Label ("HighScore: " + currenthighScore.ToString ());
if(gameOver==true)
{
GUILayout.Label("GameOver! PreesanyKey to reset!");
}
}
}
}
↧
↧
how do i make an instantiated object be a child of DontDestroyOnLoad object's child ?
i tried it and final after searching a loot i couldn't find any answer to it ..
i have a game object that contains a canvas, in that canvas i have inventory and i am dynamically adding items in to it so when ever i dynamically add new item it wont get parented to the slots and if i make the canvas not a part of DontDestroyOnLoad object then it works fine. i don't know what i am doing wrong but please help.. !
↧
Destroy on load/Properties Issue
So I have been trying and trying to resolve this issue. Basically the integer value for the color is assigned to theUI script in one scene and It is defiantly assigned. Next scene the Material changer script says that the color value is 0. Help me.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TheUI : MonoBehaviour {
private int color;
public Button multiplayer;
public Text multiplayertext;
public Button exit;
public Text exittext;
public Text ColorText;
public Dropdown ColorBox;
public Text ColorBoxText;
public Image ColorBoxArrow;
public int ColorProperty
{
get
{
return color;
}
}
private void Awake()
{
DontDestroyOnLoad(transform.gameObject);
}
private void Start()
{
ColorText.enabled = false;
ColorBox.enabled = false;
ColorBoxText.enabled = false;
ColorBoxArrow.enabled = false;
}
public void ColorSelect()
{
multiplayer.enabled = false;
exit.enabled = false;
multiplayertext.enabled = false;
exittext.enabled = false;
ColorText.enabled = true;
ColorBox.enabled = true;
ColorBoxText.enabled = true;
ColorBoxArrow.enabled = true;
}
public void Color()
{
color = ColorBox.value;
Debug.Log("the color is" + color);
}
public void Exit()
{
Application.Quit();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MaterialChanger : MonoBehaviour {
public int color;
TheUI myUI = new TheUI();
void Update () {
color = myUI.ColorProperty;
Debug.Log(color);
if (color == 4)
{
gameObject.GetComponent().material.color = Color.blue;
}
if (color == 3)
{
gameObject.GetComponent().material.color = Color.red;
}
if (color == 2)
{
gameObject.GetComponent().material.color = Color.yellow;
}
if (color == 1)
{
gameObject.GetComponent().material.color = Color.green;
}
}
}
↧
Can I add an exemption on DontDestroyOnLoad?
I am currently using DontDestroyOnLoad on my game objects. However, can I add an exemption to this? Like a particular game object will be destroyed?
↧
↧
Shared canvas for some scenes
Most of the scenes use a common canvas and eventsystem, so I add the code DontDestroyOnLoad to them. However, other scenes, such as the main menu, will use an other canvas. What's the best practice here?
↧
Destroying DontDestroyOnLoad
Hello Unity community ;) lovely as always,
Okay so here is the question:
I'm developing a multiplayer game and all is swell, so far...
But the problem is the "LobbyManager" is dont DestroyOnLoad and that's okay because it needs to be! But... after the match when all players are dead it goes back to the main menu and I need the "LobbyManager" do be removed... or it causes errors etc.
Any ideas?
Thanks in advance!
↧
Destroying Dontdestroyonload in code
Hello unity community your looking good!
Cough Cough enough of that,
Sooo here is the question:
I'm trying to destroy the dontdestroyonload after the match finishes... in my game but I have no clue how to have it destroyed.
Example of my code:
IEnumerator Finish()
{
yield return new WaitForSeconds(3.0f);
NetworkManager.singleton.StopClient();
NetworkManager.singleton.StopHost();
// DESTROY DONTDESTROYONLOAD;
SceneManager.LoadScene(0);
}
THANKS IN ADVANCE IF YOU RESPOND.
This problem is causing my game a lot of errors etc.
↧
DontDestroyOnLoad problem
Hi I'm trying to have a song start in Scene 1 and then continue through to Scene 2. But if Scene 3 happens, I want the audio to stop. I have Scene 1 to Scene 2 worked out. But for some reason I can't figure out how to stop the audio at Scene 3.
With the code below, I have the game object in Scene 1 not being destroyed on load anywhere. And that LOST bool in the Update function comes from Scene 3. If it is true, then the Audio Source of the game object in Scene 1 should be false. But it just doesn't work.
Any help would be great. Thanks!
void Start()
{
GameObject.DontDestroyOnLoad (gameObject);
loseCollider = GameObject.FindGameObjectWithTag ("LoseCollider");
}
void Update()
{
if (loseCollider.GetComponent ().LOST == true)
{
this.GetComponent().enabled = false;
}
}
↧
↧
On Click Missing Audio Object when Scene changes
Not sure if this is a common problem, but it has been frustrating me for hours.
I have a Main Menu. Two Buttons.
Play and Exit
I assign an on Click Event to the play an audio when clicked.
![alt text][1]
The Audio Source is a GameObject that I have a Do Not Destroy on load script attached to it.
When I change scenes and press by pressing play and and then change scenes again to come back to the main menu, the button loses the Game Object and says Missing Object.
![alt text][2]
Why does this occur even though the Game Object is not destroyed. Is it a different instance of this Game Object or something and Unity can't see it anymore?
[1]: /storage/temp/100195-button1.jpg
[2]: /storage/temp/100196-buttonreload.jpg
↧
Canvas will only appear on the game screen when its child of a new loaded scene canvas
So I have a gameobject which loads new scenes when nessesarry. The script attached to the game object has a variable which holds the reference to a canvas element(the canvas element has a progressbar). The problem is that after I load a new scene and I want to load a new scene in that loaded scene I lose the reference to the canvas object because I can't set him to DontDestroyOnLoad.
What I have done is I put the canvas element (see commented line in start function()) as a child of the gameobject which doesnt get destroyed.. After I have done that i dont get the warning that I have lost the object reference BUT it wont enable the canvas in the setNewNameAndLoadScene() function.
EDIT: During the runtime i have put my canvas in the new loaded scene canvas it has shown the cav. but the problem is it only works if its in the scene canvas. It does not help if I enable it. So the problem is if I make my cav a child of the new scene canvas. I lose again my reference as it is not longer attached to my gameobject.
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SceneLoaderGameObject : MonoBehaviour {
private SceneLoader sl;
public Canvas cav; //loses reference when loading new scene
void Start () {
sl = new SceneLoader ();
cav.GetComponent
↧
One SceneManager.LoadSceneAsync across multiple scenes
Hey everyone,
I'm loading a scene using SceneManager.LoadSceneAsync and it's working. Now, the scene that it's loading is huge, so I want to be able to quickly reload it if my character dies. Is there an easy way to do that?
I tried marking the object that I'm running LoadSceneAsync from as DontDestroyOnLoad, but I can't seem to reload the level from the same object that loaded the level in the first place.
Any ideas??
Thanks!
↧
DontDestroyOnLoad Duplicating Objects When Scene Reloaded
I'm aware this is a generic issue, but i'm having trouble understanding.
When I reload my scene, I want to keep an object because it has previous time records. When the scene reloads, the object is kept, but another one is created because the scene has reloaded.
How do I prevent this?
↧
↧
Do not destroy is not working ?
Hey guys have do not destroy on a game object, the do not destroy thing comes up in my hirackey yet when the next scene loads with "PhotonNetwork.loadscene"
the Object disappears and gets deleted on scene load When I need the scene to stay in play.
nothing else delete this GameObject.
'`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoNotDestroy : MonoBehaviour {
void Awake() {
DontDestroyOnLoad(transform.gameObject);
}
}`
↧
Unity Reload Scene - References missing / objects inactive upon reload
When playing the active scene, all the references are linked through inspector like the game manager
![alt text][1]
However, when reaching a simple game over and pressed the restart button, all the references (like the game manager) are missing despite that all of the objects are tucked away under the same scene I am reloading.
![alt text][2]
I remember encountering a similar question about references, but the answer seems to be unclear except for DoNoDestroyOnLoad, which is not what I want to do. nor does it solve the problem of missing references.
Is there any way that I can reload the level **EXACTLY like the first time**? Without having to use a lot of "DoNotDestroyOnLoad".
Link to similar question without clear answer.
http://answers.unity3d.com/questions/1373722/keeping-reference-after-scene-reload.html
[1]: /storage/temp/101701-screen-shot-2017-09-11-at-32243-pm.png
[2]: /storage/temp/101702-screen-shot-2017-09-11-at-31823-pm.png
↧
DontDestroyOnLoad, where is my error?
Hello,
I'm new on Unity, so to start I'm on a little project of creating a hidden object games. I'm currently doing a prototype with the key feature. I find information (specially here) and manage to have invisible button and other stuff.
I now want to work some puzzle and other stuff that need to save data. So I'm creating, to start, a simple system: when I'm using a button to load a new scene, it adds one to a variable. Once I went twice on the same page, it's over and the end scene is automatically loaded. For that, I try to use DontDestroyOnLoad, but it seems that I am facing an issue I can't find. Here is the code, have you any idea?
The script is assigned to an empty object, and I have the expected messages on the console.
What is expected:
When I switch from the scene "cuisine" to the scene "chambre", I have a variable "chambre_count " that counts how many times I went to this scene (and there is the same system for cuisine with cuisine_count).
When I went twice on the scene "chambre", it loaded another scene "fin".
The issue:
cuisine_count and chambre_count are always rebooted when I change scene and back to 0. Which means the user is never going to the scene "fin", even if yes going 50 times on the scene chambre.
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Button_Behavior : MonoBehaviour {
private int cuisine_count;
private int chambre_count;
private bool initialized;
void Start()
{
}
void Awake()
{
Debug.Log("First Lol");
if (initialized)
{
Destroy(gameObject);
Debug.Log("If Lol");
}
else
{
GameObject.DontDestroyOnLoad(gameObject);
initialized = true;
Debug.Log("Else Lol");
}
Debug.Log("Last LOL");
}
public void ChangeScene(string sceneName)
{
Addtry(sceneName);
Application.LoadLevel(sceneName);
OverGame(sceneName);
}
void Addtry(string sceneName)
{
if (sceneName == "chambre")
{
chambre_count = chambre_count + 1;
print("Nombre de fois dans la chambre " + chambre_count);
}
else if (sceneName == "cuisine")
{
cuisine_count = cuisine_count + 1;
print("Nombre de fois dans la cuisine " + cuisine_count);
}
}
void OverGame(string sceneName)
{
if (chambre_count == 2)
{
sceneName = "fin";
ChangeScene(sceneName);
}
}
}
Cheers,
Mathieu
↧
Need I put OnApplicationQuit into a DontDestroyOnLoad object?
I have some actions need to perform when the application is closed, like clearing some cached player preferences. No matter which scenes the user is, it should be executing.
Should I put it in a DontDestroyOnLoad object? or OnApplicationQuit is an event register that those code would run well even across the scenes?
Thank you.
↧
↧
dontDestroyOnLoad doesn't work as expected with scene navigation
Hi,
I am a unity nab and I can't figure out this strange behaviour i have in my test game while using `dontDestroyOnLoad`.
I have a `__preloadScene` that is my very first scene that gets loaded in the game. It only has to load my `GameSparksManager`script inside an empty `GameObject` that needs to be a singletone that never gets destroyed.
My `GameSparksManager` singletone script is this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameSparksManager : MonoBehaviour {
public static GameSparksManager instance = null;
void Start() {
Debug.Log ("ciao");
SceneManager.LoadScene("Auth Scene", LoadSceneMode.Additive);
}
private void Awake()
{
if(instance == null)
{
instance = this;
DontDestroyOnLoad(this.gameObject);
} else
{
Destroy(this.gameObject);
}
}
}
But what happen is that when you move between scenes the stuff inside them doesn't get destroyed, here an example video:
https://cl.ly/3B3o2X2K0H03
what am i doing wrong? thanks for your help
↧
HOW TO USE THE COMMAND DontDestroyOnLoad(); ?
i want to reset my game but when i use the command SceneManager.LoadScene, it resets all my scripts, variables,...
i want to keep something dont load with scene so i use dontdestroyonload but it still loads T_T
i dont know what i wronged, help me pls!!!. sorry my bad English
void Dontdestroyonload()
{
DontDestroyOnLoad(obj);
}
↧
How to initiate a counter when the script runs once it increments and once called, increments again?
How to initiate a counter when the script runs once it increments and once called, increments again?
using UnityEngine;
using System.Collections;
public class LoadWorldMapCounter : MonoBehaviour {
public static LoadWorldMapCounter Instance;
public int LoadMapCount;
// Use this for initialization
public void Awake()
{
DontDestroyOnLoad (this);
Instance = this;
// Not sure where to put or how to use this so that everytime this script runs it adds 1-->LoadMapCount++;
}
public void Start()
{
// Not sure where to put or how to use this so that everytime this script runs it adds 1-->LoadMapCount++;
}
}
↧