How to Use Enum Constraints

I’m trying to set the constraint variable of a GridLayoutGroup and I’m not understanding how to do it.

        public enum Constraint { Flexible = 0, FixedColumnCount = 1, FixedRowCount = 2 }
   

GridLayoutGroup gridParent = Canvas_Generic_ControlObj.transform.FindChild("GridParent").GetComponent<GridLayoutGroup>();
      
Constraint constraint = Constraint.FixedRowCount;
gridParent.constraint = constraint;

The above code returns error:

Assets/Scripts/FB_EditorUtils.cs(50,27): error CS0266: Cannot implicitly convert type FB_EditorUtils.Constraint' to UnityEngine.UI.GridLayoutGroup.Constraint’. An explicit conversion exists (are you missing a cast?)

Any ideas what I’m doing wrong?

I’m failing to see why I can’t just say gridParentConstraint = 2

why are you creating your own enum? shouldnt it be using this?

gridParent.constraint = GridlayoutGroup.Constraint.Flexible;//or whatever your target setting is
2 Likes

You don’t define your own enum, but use the one already in Unity. You don’t use magic numbers instead of enums because magic numbers make code not very readable.

–Eric

3 Likes

Thanks, I was not getting it at all!