2

I'm using Unity 3 to build my game. I have a basic GUI button that when clicked, I would like the user to be taken to a random level. There are 10 levels in my game. Below is a copy of the code I'm trying to implement.

function OnGUI()
{
    // Make a background box
    GUI.Box(Rect(10, 10, 100, 90), "Oracle");

    if (GUI.Button(Rect(20, 40, 80, 20), 9)) ;
    {
        Application.LoadLevel(Random.Range(0, 9));
    }
}

It's not happening. I've also tried:

function OnGUI()
{
    // Make a background box
    GUI.Box(Rect(10, 10, 100, 90), "Oracle");


    if (GUI.Button(Rect(20, 40, 80, 20))) ;
    {
        Application.LoadLevel(Random.Range(0, Application.levelCount 9));
    }
}

I've never used the Random.Range function before and somewhat confused at the proper format.

Also I have EZ GUI available and was wondering if I could enter the correct Random Range script into the 'script' dropdown or 'script with method' drop down work it, as I'd rather use a custom button. Any assistance would be greatly appreciated.

2 Answers 2

1

Here is the code that worked. I will be rebuilding and adding a few more levels I will try the straight from the Unity docs and see if the random scene loads from just the number of scenes in the build. Thanks DigitalD

static var levelCount : int;

function OnGUI () {
   // Make a background box
    GUI.Box (Rect (10,10,100,90), "ORACLE");

    if (GUI.Button (Rect (20,40,80,20), "Genie")) {
        Application.LoadLevel (Random.Range(0, Application.levelCount-5));
    }
}
0

The example code from the Unity docs should work fine. "Application.LoadLevel(Random.Range(0, Application.levelCount))" will load a random scene. The level numbers are based on the order in your build settings. Is is possible you forgot to include them in the build? Just having 10 scenes isn't enough, they'll be stripped out if they're not included in the build.

1
  • Thanks for the answer @DonavanStanley. I did have the level names and order numbers in my build. However what what jumpstarted it was changing the names of the levels from alphanumeric to integers 1-10.
    – Digital D
    Feb 12, 2011 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.