-2
\$\begingroup\$

I want to acquire scene name to apply it in a condition.

I have an int variable 'audioplay' that is going to determine which AudioClip to play.

I tried

if (Scene == "main") {
    audioplay = Random.Range (1, 3);
} else if (Scene == "menu") {
    audioplay = 3;
}

But I get the error "error CS0118: 'UnityEngine.SceneManagement.Scene' is a 'type' but a 'variable' was expected".

\$\endgroup\$
1

3 Answers 3

6
\$\begingroup\$

The SceneManagement namespace gives access to the active scene:

using UnityEngine.SceneManagement;

var currentScene = SceneManager.GetActiveScene();
var currentSceneName = currentScene.name;

In your code, I'm assuming that Scene has been returned from GetActiveScene, so you just need to change it to Scene.name.

\$\endgroup\$
0
3
\$\begingroup\$

Since this answer still appears high on Google I think it should be noted that, for multi scene projects, the current scene is not necessarily the active scene. So, this code will give the name of the scene the GameObject is currently part of:

using UnityEngine;
using UnityEngine.SceneManagement;

public class Example : MonoBehaviour
{
    void Start()
    {
        Debug.Log(gameObject.scene.name);
    }
}
\$\endgroup\$
-1
\$\begingroup\$

Been trying to do this one lately... Hope this helps :<

Here's the code for getting the current scene, I put in on my go to another scene button.

public void goToScene(string scene)
{
  SceneManager.LoadScene (scene);
  var currentScene = SceneManager.GetActiveScene(); 
  var currentSceneName = currentScene.name; 
  gotoPreviousScreen.previousScene = currentSceneName;
  Debug.Log(currentSceneName);
}

Here's the code to go to the previous scene

public void goToScene(string scene)
{
  SceneManager.LoadScene (scene);
  var currentScene = SceneManager.GetActiveScene(); 
  var currentSceneName = currentScene.name; 
  gotoPreviousScreen.previousScene = currentSceneName;
  Debug.Log(currentSceneName);
}

And this is the code where I save the scenes, which I later call

public static string previousScene;

public static bool getScene { get { return previousScene != null; } }
\$\endgroup\$
1
  • 1
    \$\begingroup\$ This seems to show exactly the same method for getting the scene name that was already covered in Griggs's answer four years ago. What new information are you hoping to add here? \$\endgroup\$
    – DMGregory
    Commented Apr 18, 2022 at 10:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .