- Home /
BoxCollider 2D not working OnMouseDown()
Hello everyone. I am kinda new to Unity, and I have a question: I can't seem to get to work a BoxCollider2D with an OnMouseDown() script attached. I have two different scenes. In the first scene, this works just fine. I set a BoxCollider2D on a image, so that when it gets clicked it changes to a new scene. While it works on scene 1, it doesn't work on scene 2. I just can't understand what is wrong. Apparently there is a problem whenever I set the box collider center x > 2. Anyway, here's the code:
using UnityEngine;
using System.Collections;
public class ChangeEnvironment : MonoBehaviour {
public int level;
void OnMouseDown(){
Debug.Log("Down");
Application.LoadLevel(level);
}
}
And here's a screenshot of the level:
Hi zeroaleph,
Are you increasing "level"? How does the image transfer to the next scene? Or if you are using two different instances of the image: are you including the script and the collider on both images? Because it's working on the first scene but not the other, compare the attributes of both images and see what differs.
As for the collider, not sure how it works, but the problem could be that you're moving only the collider and not the entire object, which will place the image and the collider on different places.
Answer by YoungDeveloper · Jun 11, 2014 at 11:19 AM
Hi, i suggest casting a ray from your touch/mouse click point forward, if it hits collider, get the data you need from it, and from this point you do whatever you want.
Hey, thanks! I can't seem to get this to work either. But that's because of my lack of dev skills I guess. I would have to cast a ray from Input.mousePosition, but in which direction? It's a 2D game... I want to be able to have more than one collider per environment, so if I have to tag every single collider individually to get them it becomes overly complicated. Can I ask you for the code of what you proposed?
unchecking is trigger doesn't make any difference, and I don't see why it should have anyway :)
if(Input.GetButtonDown("Fire1")){
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.Log("Click");
if(Physics.Raycast(ray, hit)){
Debug.Log("Ray hit something");
}
}
You dont need to use tag for every item, create seperate script which will hold the index number of what type of item is that.
Thanks a lot, but I don't know why, it doesn't work. It detects the click, but it does not hit the collider even if I click on it. (Oh, btw I changed the Physics.Raycast(ray,hit) to Physics.Raycast(ray, out hit)) :( I just don't understand why...