The question is answered, right answer was accepted
Loading random scenes, but never the same
Hello guys, I am pretty much a total beginner with Unity and I am currently trying to figure out a script for a VR experiment I am trying to create. I already managed to randomize the scenes and implement a timer. Now my question is, how can I prevent the same scene from appearing twice and make it so that one run only goes through every scene once? This is my code so far:
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadingAfterTime : MonoBehaviour
{
[SerializeField]
private float delayBeforeLoading = 10f;
private float timeElapsed;
private void Update()
{
timeElapsed += Time.deltaTime;
if (timeElapsed > delayBeforeLoading)
{
int index = Random.Range(1, 4);
SceneManager.LoadScene(index);
}
}
} ,
Answer by Hellium · Apr 11, 2019 at 09:15 PM
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
public class LoadingAfterTime : MonoBehaviour
{
private static List<int> scenes = new List<int>(){ 1, 2, 3, 4 } ;
[SerializeField]
private float delayBeforeLoading = 10f;
private float timeElapsed;
private void Start()
{
if( scenes.Count <= 0 )
{
Debug.LogWarning( "No remaining scene to load" ) ;
enabled = false;
}
}
private void Update()
{
timeElapsed += Time.deltaTime;
if (timeElapsed > delayBeforeLoading)
{
int index = Random.Range(0, scenes.Count);
int scene = scenes[index];
scenes.RemoveAt( index ) ;
SceneManager.LoadScene(scene);
}
}
}
Thank you for the quick response, really appreciated. Unfortunately I get the message "Cannot implicitly convert type float' to `int'. An explicit conversion exists (are you missing a cast?)". Any explanation why this happens?
okay just added (int) to the "int scene = (int)scenes[index];" row and it magically works, hope that was right :) Thanks a lot again for your effort!
$$anonymous$$y bad, I don't know why I declared scenes
as a List of floats, ins$$anonymous$$d of a list of integers. Fixed it so you don't have to cast.
I don't want to harrass you, but if I want some end scene to play after the last scene has played, how would I go about that? I tried to just add Scene$$anonymous$$anager.Loadscene("scenename") to the conditional scenes.Count statement, but everytime it loads the last scene, it would just immediately skip to the end scene without delay. Do i just need to add another scenes.Count statement but with another value, if that makes sense?
Follow this Question
Related Questions
How to switch to next level after completeing the task in current level 6 Answers
Unity 5.0.2 - How can I know when a scene is loaded AND when it's running well? 0 Answers
Resources.Load taking very long on Android 0 Answers
Unity Editor Not Starting/Not Responding 1 Answer
Async Level loading issue. 0 Answers