Search Unity

Syntax question: Setting Canvas Scaler properties

Discussion in 'Scripting' started by Denisowator, Mar 6, 2019.

  1. Denisowator

    Denisowator

    Joined:
    Apr 22, 2014
    Posts:
    918
    I'm initializing a canvas GameObject, and I want it to have the same components and properties as my main canvas (only difference being the sort order).
    upload_2019-3-6_17-38-31.png

    I already have the Canvas component added with its properties. But I'm scratching my head confused and frustrated, because there doesn't seem to be any proper documentation on setting things like the Canvas Scaler properties.

    I don't know if it's just me lacking some basic knowledge, or whether it really is due to lack of documentation.

    As an example, here's what I tried for setting the UI Scale Mode:
    Code (CSharp):
    1. canvasScaler.GetComponent<CanvasScaler>().uiScaleMode = ScaleMode(ScaleWithScreenSize);
    2.  
    3. canvasScaler.GetComponent<CanvasScaler>().uiScaleMode = ScaleMode("ScaleWithScreenSize");
    4.  
    5. canvasScaler.GetComponent<CanvasScaler>().uiScaleMode = "ScaleWithScreenSize";
    6.  
    7. canvasScaler.GetComponent<CanvasScaler>().uiScaleMode = ScaleWithScreenSize;
    8.  
    9. canvasScaler.GetComponent<CanvasScaler>().uiScaleMode.ScaleWithScreenSize;
    10.  
    11. canvasScaler.GetComponent<CanvasScaler>().uiScaleMode(ScaleWithScreenSize);
    12.  
    13. canvasScaler.GetComponent<CanvasScaler>().uiScaleMode("ScaleWithScreenSize");
    Each one gives me some sort of error. I also tried without the whole "GetComponent" part.

    Could anyone also help me out with the rest of the Canvas Scaler properties?

    P.S. "canvasScaler" is a variable name for a CanvasScaler which I'm adding with:
    Code (CSharp):
    1. canvasScaler = canvasObj.AddComponent<CanvasScaler>();
     
    Last edited: Mar 6, 2019
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,736
    If canvasScaler is already the CanvasScaler object you're looking for, you don't need to GET it again.

    To set its value you use:

    Code (csharp):
    1. canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
     
    Denisowator likes this.
  3. Denisowator

    Denisowator

    Joined:
    Apr 22, 2014
    Posts:
    918
    Thank you so much!
     
    Kurt-Dekker likes this.