Hello! I’m making a main menu for a game, and I’m trying to load a level called, “Slender Woods” when the player clicks a quad. The quad is called, “Menu Button 1.” By the way, I’m very very new to Unity (this is my first game), and I’m only using Unity 5 Personal. This is the script I attached to the quad.
function MB1() {
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Input.GetMouseButtonDown) {
if(Physics.Raycast(ray, hit, 100)){
if (hit.transform.tag == "Menu Button 1") {
Application.LoadLevel("Slender Woods");
}
}
}
}
When I test the game, everything pops up (no errors), but nothing happens when I click the button. Please help, and sorry if this is a very noob-ish problem.
I think that you need to place input and raycast inside update function and place this script on the camera not on the obect.
Something like:
function Update(){
if(Input.GetMouseButtonDown) {
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, hit, 100)){
if (hit.transform.tag == "Menu Button 1") {
Application.LoadLevel("Slender Woods");
}
}
}
}
Another usefull thing would be to use a switch case to identify objects that are clicked:
function Update(){
if(Input.GetMouseButtonDown) {
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, hit, 100)){
switch(hit.collider.name){
case "Menu Button 1":
Application.LoadLevel("Slender Woods");
break;
case "Menu Button 2":
Application.LoadLevel("Slender Woods2");
break;
//and so on
}
}
}
}
Hope this helps.
That can be solved very easily using OnMouseDown.
Just add the script to your object that has a collider.
Next, just edit levelname in inspector.
// Remember to edit Level Name in the Inspector
// after you have placed the script on the Collider.
var levelName : String = "untitled";
// OnMouseDown will be called by Unity.
// No other code is required.
function OnMouseDown()
{
Application.LoadLevel(levelName);
}
Unity takes care of raycasting etc for you.