I am making a 2D card game. Each card is a prefab object, with the rectangular card background in the default layer and the text as a canvas child in the UI layer. I ran into a problem of the text from one card overlapping the text from another card. This picture shows the problem.
I toggled with the layer settings and somehow managed to achieve the desired effect with one of the card prefabs. This picture shows the end result I am trying to achieve.
I tried replicating the settings for the correct card prefab in the inspector.
Both green card prefabs have the exact same setting for canvas and sprite renderer component, like in the screenshots above. However, I might have changed something else i’m not aware of because when I duplicated the prefab with the desired behaviour, it worked.
Other than experimenting with layer settings, I tried using the API too as an alternative. This is a script I tried but it is not working because the canvas text sorting order does not get updated (and stays 0), while background card prefab increments correctly. The result is the text is hidden behind the card background…
private SortingGroup sortingGroup;
private GameObject parentObject;
private void Awake()
{
parentObject = this.gameObject;
collider2d = GetComponent<Collider2D>();
canvas = GameObject.FindGameObjectWithTag("MainCanvas").GetComponent<Canvas>();
sortingGroup = GetComponent<SortingGroup>();
}
public void OnBeginDrag(PointerEventData eventData)
{
collider2d.enabled = false;
// Bring the dragged card to the top
if (sortingGroup != null)
{
sortingOrderCounter++;
sortingGroup.sortingOrder = sortingOrderCounter;
foreach (Canvas childCanvas in parentObject.GetComponentsInChildren<Canvas>())
{
childCanvas.overrideSorting = true;
childCanvas.sortingOrder = sortingOrderCounter;
}
}
}
I need another solution because my canvas isn’t a nested canvas, and the text is set to inactive when the card is flipped the other side, then back to active again when flipped back, which makes it complicated. What’s the easiest way to fix this problem? Thank you very much.