0

I have 2 scenes in my project, MainMenu and Game.

Main Menu Image

Game Image

MainMenu scene contains 2 buttons, 'Hide Black' and 'Hide White'. Game scene contains 2 panels, 'Black' and 'White'. When the user clicks any of button from main menu, I wanna hide the corresponding panel in Game scene and also load the scene. This is the script for the same.

using UnityEngine;
using UnityEngine.SceneManagement;

public class MainMenu : MonoBehaviour { public void HideBlack() { SceneManager.LoadScene(1); GameObject black = GameObject.Find("Black"); black.SetActive(false); }

public void HideWhite() {
    SceneManager.LoadScene(1);
    GameObject white = GameObject.Find("White");
    white.SetActive(false);
}

}

But it turns out that GameObject.Find can't find the panels in my Game scene. I looked my forums for help but I find them confusing. What's going on here?

EDIT - This is not from my actual project. I created these scenes just to explain the problem better. I must use 2 scenes in my actual project as I have 3D objects in Game scenes.

1 Answers1

0

I just figured in out. I wanted to load the same scene but with different UI on two different options. So I needed to hide other UI elements. To solve my problem I assigned Hide.cs script to an empty game object in my Game scene.

using UnityEngine;

public class Hide : MonoBehaviour { public GameObject black, white; public static bool hideBlack;

void Start() {
    if(hideBlack) {
        black.SetActive(false);
    } else {
        white.SetActive(false);
    }
}

}

And this is MainMenu.cs

using UnityEngine;
using UnityEngine.SceneManagement;

public class MainMenu : MonoBehaviour { public void HideBlack() { Hide.hideBlack = true; SceneManager.LoadScene(1); }

public void HideWhite() {
    Hide.hideBlack = false;
    SceneManager.LoadScene(1);
}

}

  • It is generally not advised to use static fields for setting state of objects. It works for now but as your game progresses, it might introduce scaleability issues. What if you create third color? How will you select which ones to hide? – eLTomis Jul 15 '20 at 13:51
  • Okay. I'll use interger instead of bool – Manoj Bhatt Jul 15 '20 at 19:15