how to change value of Canvas.overrideSorting?

how to change value of Canvas.overrideSorting in script?

Canvas canvas = gameObject.GetComponent();
canvas.overrideSorting = true;

above code doesn’t work :frowning:

To highlight @eab6863’s comment, note that I had the same problem of overrideSorting not being set via script when the “when the GameObject the Canvas component is attached to is not active in the hierarchy.”


In my case, I was able to work around the problem by making sure the canvas is enabled first by setting the canvas overrideSorting property in OnEnable:

private void OnEnable()
{
    GetComponent<Canvas>().overrideSorting = true;
}

Notes

  1. I am using Unity 2017.3

  2. I got this response from Unity QA (on August 28, 2018) that this is not a bug and working as intended:

Thanks for reporting the issue.

I’m sorry to tell you that this is not
a bug. I’ve talked to developers and
did some research and found this:

"The GameObject must be active in the
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."

I know this is an old question but it is what is coming up for me when searching so I will leave some advice here.
first when you are declaring your variable you need to tell it what component to get

Canvas canvas = gameObject.GetComponent<Canvas>();

Then you should be able to use it as a variable correctly.

 canvas.overrideSorting = true;