- Home /
Touch button to load scene, instead of touching anywhere on screen
I'm creating a 2D game for iOS using Sprites, and have a 'Play' button on the main menu scene. I want to load the next screen when the play button is tapped, and have used the following script:
function Update(){
if ((Input.touchCount == 1) &&
(Input.GetTouch(0).phase == TouchPhase.Began) )
{
Application.LoadLevel("level1");
}
}
The code works fine, but when the screen is tapped anywhere, 'level1' is loaded. I just the button to register the input. I attached the code to the sprite which I am using for my button, and also tried attaching it to a gameobject infront of the sprite, but with no mesh renderer. I can still tap anywhere on the screen to load the next level, but only want to load level if the button is pressed.
Any ideas how to prevent this?
Thanks.
@ahaykal hi i was having the same issue and tried your code but I still find that level loads no matter where on screen i touch. Also, I have three buttons, each selects a different player. I wrote three different scripts, one for each button and placed it on relevant game object, but no matter where on the screen i touch, always the same level will load. Please help
Answer by ahaykal · Apr 22, 2013 at 03:55 PM
function Update () {
for(var i:int = 0; i < Input.touches.Length; i++)//How many touches do we have?
{
var touch:Touch = Input.touches[i];//The touch
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://if the touch begins
Application.LoadLevel("level1");
break;
}
}
}
}
}
Try this one. It is untested though.
Your answer
Follow this Question
Related Questions
Change to scene based on current scene 1 Answer
Touch controls not working after reloading a scene. 1 Answer
Android: Scene change (Application.LoadLevel) has no effect 3 Answers
LoadLevel easy i know, but not working. 1 Answer
How to make a character move towards a side of the screen that's pressed at a constant rate? 2 Answers