Search code examples
c#unity-game-engine3dscene-manager

Can i change the scene (value?) via public void or something? I do not want to make a new code everytime and change the scene that is going to load


This is the code i am using. It switches to another scene if the goal gets touched by an objekt with the right tag. Now I want to know how i can change the numbers of the scenes via unity without opening the code.

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class levelend: MonoBehaviour
{
    [SerializeField]
    string strTag;

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.tag == strTag)
            SceneManager.LoadScene(1);
    }
}

Solution

  • Edit: oh i just saw you only want to change it in the editor, just create a public variable, the variable can then be changed in the unity editor

    public int levelNumber = 1;
    
    private void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.tag == strTag)
               SceneManager.LoadScene(levelNumber);
        }
    
    if you want to have an object that persists you can use the `DontDestroyOnLoad(GameObject)`[1] object methode. for example:
    void Awake(){
         DontDestroyOnLoad(this)
    }
    

    if there is a chance that the object already exist in another scene make sure to check beforhand if an object exist and destroy the unwanted object. Also, change your LoadScene code. Currently you are always loading 1. If your scenes are numerated from 1 to x you could just use an int x = 1; and add x++; to is. for example:

    private void OnCollisionEnter(Collision collision)
        {
            if (collision.collider.tag == strTag)
                x++;
                SceneManager.LoadScene(x);
        }
    

    if your scenes are not numerated you could for example use an string Array or something and just iterate over that.

    [1]https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html