- Home /
How to create a sprite button to load level when touched
Hi I have a menu screen with three game objects, each representing a game character to select. Touching a character should result in relevant level load, but at the moment "levelone" loads no matter where on screen i touch (including if I touch the other game object, which should load "leveltwo" or "levelthree" respectively. This is the code I am using:
function Update () {
for(var i:int = 0; i < Input.touches.Length; i++)
{
var touch:Touch = Input.touches[i];
var ray:Ray = Camera.main.ScreenPointToRay(touch.position);
var hit:RaycastHit = new RaycastHit();
if(Physics.Raycast(ray,hit, 1000))
{
if(hit.collider.gameObject == this.gameObject)
{
switch(touch.phase)
{
case TouchPhase.Began:
Application.LoadLevel("levelone");
break;
}
}
}
}
}
You said that it's loading level one regardless of where you tap on the screen. So I suggest you add the following before line 9, as it will tell you what's actually being hit. (If you've got debugging working, then you can just set a breakpoint.)
Debug.Log("Game object hit: " + hit.collider.gameObject.name);
I assume that you have a "leveltwo" and a "levelthree" version of this script - yes? If so, you may want to consider declaring a public field, e.g. "LevelToLoad". Unity will then show that field in the Inspector allowing it to be set more easily. That way you'll only have one script to manage.
Your answer
![](https://koobas.hobune.stream/wayback/20220613152320im_/https://answers.unity.com/themes/thub/images/avi.jpg)