- Home /
Best way to load a level depending on which game object is clicked
Hey guys,
I've got 50 levels in a game. I have 50 "buttons" in my menu screen. When I click on a specific button I want a specific level to load. Rather than attaching a script to each game object to load a specific level I'm thinking of creating an array for all of the buttons and then using the OnClick function in NGUI. Right now my code is not working at all though. What I've got is this (I know it's wrong but I'm trying to figure out the right way to do it) :
public GameObject[] button;
void OnClick() {
if (button[0])
Application.LoadLevel(3);
if (button[1])
Application.LoadLevel(4);
if (button[2])
Application.LoadLevel(5);
if (button[3])
Application.LoadLevel(6);
if (button[4])
Application.LoadLevel(7);
if (button[5])
Application.LoadLevel(8);
etc.....
Any suggestions about a good way to go about doing this?
Answer by stingman · May 20, 2012 at 03:57 AM
I thought of another way of doing this. Here is what I came up with. I just attached another script called Button with the following public variables for reference. Works perfect.
using UnityEngine;
using System.Collections;
public class MenuButtonLoadLevel : MonoBehaviour {
RaycastHit hit;
public int level;
void Update() {
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.gameObject.GetComponent<Button>().attribute == "level")
{
level = hit.collider.gameObject.GetComponent<Button>().levelNumber;
Application.LoadLevel(level);
}
}
}
}
}