Search code examples
c#unity-game-engineunity-ui

Cannot change Canvas.overrideSorting property


Very odd problem, I have a Canvas object and I am trying to set the overrideSorting flag to true.

public void SetSortingLevel(string sortinglayerName)
{
    _canvas.overrideSorting = true;
    _canvas.sortingLayerName = sortinglayerName;
}

However, normally this works, however if I put a breakpoint and look at the code, even right after setting the override to true, it is false:

enter image description here

The api shows this is just a setter/getter. Any idea why this is happening?

I have used this code before and it normally works.

Note: This is a nested canvas so it should be allowed to have its sorting layer set.

Answer: As noted in the answer below, the activeInHierarchy check turns out to be false.


Solution

  • This is by design. You can only change the value of Canvas.overrideSorting on nested canvas.

    For example, if you have a Canvas which is root of other canvas or UI Objects, you won't be able to change the value of Canvas.overrideSorting.

    If you have any Canvas which is a child of other Canvas, you will be able to change the value of Canvas.overrideSorting.

    Requirements for changing Canvas.overrideSorting:

    1.Canvas which is a child of other Canvas

    • Canvas //cannot change
      • Canvas //can change
        • Canvas //can change

    2.The GameObject must be active in hierarchy and the Canvas component must be enabled in order to can change Canvas.overrideSorting.

    Active in hierarchy means that all the parent Canvas GameObject of the Canvas you want to change its Canvas.overrideSorting must be active and the Canvas script itself must be enabled. This can be verified with the gameObject.activeInHierarchy property.

    If Canvas.gameObject.activeInHierarchy is not true, you cannot set or change the Canvas.overrideSorting property. It is better to check those properties before attempting to change Canvas.overrideSorting.

    if (_canvas.gameObject.activeInHierarchy && _canvas.enabled)
        _canvas.overrideSorting = true;
    else
        Debug.Log("Cannot change Canvas overrideSorting");