- Home /
Make Mouse Click Ignore Object
I have a problem where I have collectible objects which randomly spawn and enemies that wander around....occasionally an enemy will wander over a collectible meaning that if the player click on it they are clicking on the enemy and not on the collectible.
I have my objects on type of Object, Helpful Chars, Enemies, and Collectibles. They are all on different layers and I have tried layermasks.
Layer 8 Enemies Layer 9 Friendly Chars Layer 10 SunOrbs Layer 11 Ground
I have had it so that the raycast only pics up collectibles when mouseover, but this did not make any difference.
I have 2 scripts...One is to keep control of the mouse position and the raycasts
This is the GetMousePosition script
static var MousePositionIn3DSpace: Ray;
static var hit : RaycastHit;
var layer : int = 10;
var layer2 : int = 11;
var maskingLayers : int;
var maskingLayers2 : int;
var sunOrbMask : int;
function Update(){
// Set all layers except layer 10 and 11 is visible to raycast
maskingLayers = 1 << layer;
maskingLayers2 = 1 << layer2;
sunOrbMask = maskingLayers| maskingLayers2;
Debug.Log(Get_Mouse_Position.hit.collider); // This shows that it is finding SunOrb
MousePositionIn3DSpace = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (MousePositionIn3DSpace, hit, 100,sunOrbMask)) {
Debug.DrawLine (MousePositionIn3DSpace.origin, hit.point);
}
}
Second Script is the Collectible Object script
function OnMouseDown(){
if (Get_Mouse_Position.hit.collider == "SunOrb"){
Level_1.sunOrbPower = Level_1.sunOrbPower+5;
Destroy(gameObject);
}
}
If anyone can help with this it would be appreciated. I am new to Unity and Coding coming from a pure design background so please explain in simple terms.
Thanks
Answer by Waz · Jun 21, 2011 at 11:11 PM
A Raycast with the layer mask set should work, if the colliders of the items are on the layers you suggest, so you need to post code so we can see what you're doing wrong. Another option is to use RaycastAll, but note that the return is not ordered in any way, you need to sort or search it for your relevant object.
I have updated the post with some more information and code.
Answer by Waz · Jun 22, 2011 at 12:35 AM
The problem is that your call to Raycast will trash your previous hit value even if nothing is hit. A quick fix is probably to only assign to hit if the hit occurs:
var tmp : RaycastHit;
if (Physics.Raycast(... tmp ...)) { hit = tmp; }