user4221984
user4221984

Reputation:

Unity Check if object is clicked

Please keep in mind that I'm new to unity. I created an 2D android game app.

I created a start button( from an image) and attacted a Box colider, and a C# script to it.

When I click the "button" I want the program to move to the next "Level", that Works except that I want it to only Work if i click the object and not everywhere on the game.

This is the C#:

using UnityEngine;
using System.Collections;

public class StartGame : MonoBehaviour {


// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButtonDown(0)) {
        Application.LoadLevel("Game");
    }

}

}

I searched alot about this and maybe people say that to solve this you have to use, Ray and RaycastHit But I cant get that to Work either.

Here is what I tried to with Ray & RaycastHit

// Update is called once per frame
void Update () {
    if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) || (Input.GetMouseButtonDown(0))) 
    {
        RaycastHit hit;

        Ray ray;

        #if UNITY_EDITOR
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        #elif (UNITY_ANDROID || UNITY_IPHONE || UNITY_WP8)
        ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
        #endif

        if(Physics.Raycast(ray, out hit))
        {
            Application.LoadLevel("Game");
        }
    }
}

Any help would be so appriciated.

Upvotes: 1

Views: 7888

Answers (1)

maZZZu
maZZZu

Reputation: 3615

Probably the easiest way is to add box collider and script component including function below to the gameobject.

void OnMouseOver()
{
    if (Input.GetMouseButtonDown(0))
    {
        Application.LoadLevel("Game");
    }
}

Edit:

I'm guessing that the original code is not working on your scene, because you are using box collider 2d. Physics.Raycast is testing against 3D colliders. When I run it with the 3D version box collider it works fine.

Upvotes: 7

Related Questions