C# 2D Click on Object touching trigger
How can I click on an object that is touching a trigger?
The current issue is that it just recognizes the trigger, and since the objects are intertwining, it only recognizes one of them, being this case the trigger.
I am using both as I need to create a click area and a non click area.
Could anyone point out on what I could use? Thanks in advance.
You can use custom raycasts with masks to detect the clicks while ignoring objects that are not required. If you can give some more information (screenshots / layout), it might be easier to suggest something. Cheers !
Thanks for the help so far! Can you understand it with this image?
Answer by snorcack · Nov 11, 2016 at 01:12 PM
Based on the image provided, I am giving a basic solution with certain assumptions. 1 - The green object and the trigger have some sort of script or tag that can differentiate it. 2 - These are sprites and not canvas objects.
Attach a script to green object that calls your onclick function. Put in a bool that sets true or false on the "OnTriggerExit" and "OnTriggerEnter" methods.
Do a custom "GetRayIntersectionAll" to get all the 2d colliders at the mouseclick. If you get the green object, call the onclick function on it. If it had entered the trigger, the bool would be false and the function would not be called.
Let me know if this is in the direction you wanted or if I have oversimplified things for myself.
Hello again, and thanks for the help so far. I am having an issue with getting Unity to even recognize my Layermasks. I have a on mouseClick and am trying to get a hit only on the prefabs of the greenObject type, which is Layer$$anonymous$$ask 8. So I tried:
However I am not getting any results. The click works as I have tested , however it does not recognize the prefabs of "greenObject". Could you tell me whats wrong?
void Update()
{
if(Input.Get$$anonymous$$ouseButtonDown(0))
{
Ray r = gCamera.ScreenPointToRay(touchPosition);
RaycastHit hit;
if (Physics.Raycast(r, out hit, $$anonymous$$athf.Infinity, 1<<8))
{
Debug.Log("greenObject");
}
}