Many times I have 2 GOs one over another, different sorting layer, and I click over the top(the one with the higher sorting layer) but it doesn’t find collision with it but with the one behind. So my question is how can I fix it without deactivating the colliders of the rear GO?
Simple example- Screenshot by Lightshot
so in this case for example if I click on the button “R” sometimes finds collision with the platform not the button and the platform is in sorting layer 1 and the button 2, but still if I deactivate the collider of the platform, the player is going to fall through it.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public enum SortingLayers { FirstLayer, SecondLayer, ThirdLayer, Fourth, RunTimeMenu, BlackScreen, GameIntro}
public class SortingLayerManager : MonoBehaviour {
private static Dictionary<string, int> SortingLayers = new Dictionary<string,int>(10);
void OnEnable()
{
SortingLayers.Add("FirstLayer", 0);
SortingLayers.Add("SecondLayer", 1);
SortingLayers.Add("ThirdLayer", 2);
SortingLayers.Add("FourthLayer", 3);
SortingLayers.Add("RunTimeMenu", 4);
SortingLayers.Add("BlackScreen", 5);
SortingLayers.Add("GameIntro", 6);
}
private static int Compare(GameObject gameObject1, GameObject gameObject2)
{
string layer1 = gameObject1.renderer.sortingLayerName,
layer2 = gameObject1.renderer.sortingLayerName;
if (SortingLayers[layer1].CompareTo(SortingLayers[layer2]) == 0)
{
return gameObject1.renderer.sortingOrder.CompareTo(gameObject2.renderer.sortingOrder);
}
return SortingLayers[layer1].CompareTo(SortingLayers[layer2]);
}
public static bool IsTopmost(GameObject go)
{
RaycastHit2D[] hits;
Vector3 wp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
wp.z = Camera.main.transform.position.z;
hits = Physics2D.RaycastAll(wp, Vector2.zero, Vector3.Distance(Camera.main.transform.position, go.transform.position) * 2);
if (hits.Length == 0)
{
return false;
}
GameObject topMostSoFar = hits[0].collider.gameObject;
RaycastHit2D hit;
for (int i = 1; i < hits.Length; i++)
{
hit = hits*;*
if (Compare(topMostSoFar, hit.collider.gameObject) == -1)
{
topMostSoFar = hit.collider.gameObject;
}
}
return topMostSoFar == go;
}
}
I came up on my own with this solution, and whenever I check for click I call the IsTopmost method and if it is then I do the logic.