- Home /
Unity - How to activate a canvas or gameobject when a scene restarts?
I have one scene which has many levels when i am playing and i want to restart this level i am loading the scene and activating the gameobject of the this level. But the scene restarts without activating the gameobject of that level. Here is my code
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayLevel : MonoBehaviour {
// Use this for initialization
GameObject Level;
public GameObject Menus;
Button button;
void Start ()
{
button = GetComponent<Button> ();
button.onClick.AddListener(delegate() {
this.Restart();
});
Level = GameObject.FindGameObjectWithTag ("Levels");
Debug.Log (Level.name);
}
// Update is called once per frame
void Update () {
}
public void Restart()
{
Time.timeScale = 1;
SceneManager.LoadScene (SceneManager.GetActiveScene().name);
Debug.Log (Level.name);
Menus.SetActive (false);
Level.gameObject.SetActive (true);
}
}
Answer by game4444 · Sep 19, 2017 at 05:15 AM
Hi, one thing can you confirm please, Debug.Log in restart is printing levelName or not? What i think you should activate level gameObject in start function. Because when ever you will reLoad scene. It will reset your all values and conditions. One thing you could do make public static bool reStart and set value true when you are pressing restart button. And in start check if (reStart == true) then activate level. and after activating on next line set bool to false. Public static bool keeps its value on reloading scene.
I have a canvas and it has many panels for level messages i gave the Levels tag to all the panels but the debug.log line is giving me an error of null reference.
Answer by NorthStar79 · Sep 19, 2017 at 05:15 AM
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayLevel : MonoBehaviour {
// Use this for initialization
GameObject Level;
public GameObject Menus;
Button button;
void Start ()
{
button = GetComponent<Button> ();
button.onClick.AddListener(delegate() {
this.Restart();
});
Level = GameObject.FindGameObjectWithTag ("Levels");
Debug.Log (Level.name);
Menus.SetActive (false);
Level.gameObject.SetActive (true);
}
// Update is called once per frame
void Update () {
}
public void Restart()
{
Time.timeScale = 1;
SceneManager.LoadScene (SceneManager.GetActiveScene().name);
}
}
changes you made resets too when you reload a scene, activating that objects in start maybe solve your problem .
It restarts the scene without activating the level gameobject same as before.
The debug.log successfully prints the name of the level but when the scene restarts the level gameobject is not activated nor the menus gameobject deactivates.
Nope but i think its the execution problem the debug line prints very quickly then the scene reloads.