Пример #1
0
 // Use this for initialization
 void Start()
 {
     mGroup = (GridLayoutGroup)this.GetComponent("GridLayoutGroup");
     InitPlayers();
 }
Пример #2
0
    public void updateSlotAmount()
    {
        if (prefabSlot == null)
        {
            prefabSlot = Resources.Load("Prefabs/Slot - Inventory") as GameObject;
        }

        if (SlotContainer == null)
        {
            SlotContainer = (GameObject)Instantiate(prefabSlotContainer);
            SlotContainer.transform.SetParent(PanelRectTransform.transform);
            SlotContainerRectTransform = SlotContainer.GetComponent <RectTransform>();
            SlotGridRectTransform      = SlotContainer.GetComponent <RectTransform>();
            SlotGridLayout             = SlotContainer.GetComponent <GridLayoutGroup>();
        }

        if (SlotContainerRectTransform == null)
        {
            SlotContainerRectTransform = SlotContainer.GetComponent <RectTransform>();
        }
        SlotContainerRectTransform.localPosition = Vector3.zero;

        List <Item>       itemsToMove = new List <Item>();
        List <GameObject> slotList    = new List <GameObject>();

        foreach (Transform child in SlotContainer.transform)
        {
            if (child.tag == "Slot")
            {
                slotList.Add(child.gameObject);
            }
        }

        while (slotList.Count > width * height)
        {
            GameObject   go         = slotList[slotList.Count - 1];
            ItemOnObject itemInSlot = go.GetComponentInChildren <ItemOnObject>();
            if (itemInSlot != null)
            {
                itemsToMove.Add(itemInSlot.item);
                ItemsInInventory.Remove(itemInSlot.item);
            }
            slotList.Remove(go);
            DestroyImmediate(go);
        }

        if (slotList.Count < width * height)
        {
            for (int i = slotList.Count; i < (width * height); i++)
            {
                GameObject Slot = (GameObject)Instantiate(prefabSlot);
                Slot.name = (slotList.Count + 1).ToString();
                Slot.transform.SetParent(SlotContainer.transform);
                slotList.Add(Slot);
            }
        }

        if (itemsToMove != null && ItemsInInventory.Count < width * height)
        {
            foreach (Item i in itemsToMove)
            {
                addItemToInventory(i.itemID);
            }
        }

        setImportantVariables();
    }
Пример #3
0
    public void generateMenu()
    {
        blocks = new List <PropertyMenuBlockManager>();
        int count = transform.childCount;

        for (int i = 0; i < count; i++)
        {
            GameObject.DestroyImmediate(transform.GetChild(0).gameObject);
        }

        grid = GameObject.Instantiate(Resources.Load("UI/PropertyPanel") as GameObject, transform);

        PropertyInfo[] props = GetProperties();

        GridLayoutGroup gridlayout   = grid.GetComponent <GridLayoutGroup>();
        float           screenwidth  = generateAtRuntime ? Screen.width : 1920;
        float           screenheight = generateAtRuntime ? Screen.height : 1080;
        float           blocky       = Mathf.Max(80, screenheight / (props.Length + 1));

        gridlayout.cellSize = new Vector2(screenwidth * 0.4f, blocky);
        gridlayout.spacing  = new Vector2(screenwidth * 0.1f, -(screenheight - blocky * (props.Length + 1)) / 2);
        gridlayout.padding  = new RectOffset((int)(screenwidth * 0.05f), 0, (int)blocky / 2, (int)blocky / 2);



        foreach (PropertyInfo p in props)
        {
            string propertyname = p.Name;
            string easyname     = "";
            if (propertyname != ThemePropertyName)
            {
                object[] attrs = p.GetCustomAttributes(true);
                foreach (Attribute a in attrs)
                {
                    if (a.GetType().ToString() == "PropertyRename")
                    {
                        PropertyRename rnm = a as PropertyRename;
                        easyname = rnm.easyname;
                    }
                }
                GameObject g = null;
                if (p.PropertyType == typeof(int))
                {
                    g = GameObject.Instantiate(Resources.Load("UI/PropertyMenuBlockNumber") as GameObject, transform.GetChild(0));
                    g.GetComponent <PropertyMenuBlockManager>().SetUp <int>(propertyname, (int)p.GetValue(configurationschema), generateAtRuntime, easyname);

                    foreach (Attribute a in attrs)
                    {
                        if (a.GetType().ToString() == "PropertyRange")
                        {
                            PropertyRange r = a as PropertyRange;
                            g.GetComponent <PropertyMenuBlockManager>().SetUpLimits(r.min, r.max);
                        }
                    }
                }
                if (p.PropertyType == typeof(float))
                {
                    g = GameObject.Instantiate(Resources.Load("UI/PropertyMenuBlockNumber") as GameObject, transform.GetChild(0));
                    g.GetComponent <PropertyMenuBlockManager>().SetUp <float>(propertyname, (float)p.GetValue(configurationschema), generateAtRuntime, easyname);

                    foreach (Attribute a in attrs)
                    {
                        if (a.GetType().ToString() == "PropertyRange")
                        {
                            PropertyRange r = a as PropertyRange;
                            g.GetComponent <PropertyMenuBlockManager>().SetUpLimits(r.min, r.max);
                        }
                    }
                }
                if (p.PropertyType == typeof(string))
                {
                    foreach (Attribute a in attrs)
                    {
                        if (a.GetType().ToString() == "PropertyLimitedSet")
                        {
                            PropertyLimitedSet s = a as PropertyLimitedSet;
                            g = GameObject.Instantiate(Resources.Load("UI/PropertyMenuBlockDropdown") as GameObject, transform.GetChild(0));
                            List <string> ls = new List <string>();
                            ls.AddRange(s.values);
                            g.GetComponent <PropertyMenuBlockManager>().SetUp <string>(propertyname, s.values[0], generateAtRuntime, easyname, ls);
                        }
                        else if (a.GetType().ToString() == "PropertyReferenceFolder")
                        {
                            PropertyReferenceFolder prf = a as PropertyReferenceFolder;
                            g = GameObject.Instantiate(Resources.Load("UI/PropertyMenuBlockDropdown") as GameObject, transform.GetChild(0));
                            List <string> ls = new List <string>();
                            foreach (string f in Directory.GetFiles(Application.streamingAssetsPath + "/" + prf.folder))
                            {
                                string file = f.Split('/').Last().Split('\\').Last();
                                if (file.EndsWith(prf.extension))
                                {
                                    ls.Add(file);
                                }
                            }

                            g.GetComponent <PropertyMenuBlockManager>().SetUp <string>(propertyname, ls.First(), generateAtRuntime, easyname, ls);
                        }
                        else
                        {
                            g = GameObject.Instantiate(Resources.Load("UI/PropertyMenuBlockText") as GameObject, transform.GetChild(0));
                            g.GetComponent <PropertyMenuBlockManager>().SetUp <string>(propertyname, "", generateAtRuntime, easyname);
                        }
                    }
                }
                if (p.PropertyType == typeof(bool))
                {
                    g = GameObject.Instantiate(Resources.Load("UI/PropertyMenuBlockBool") as GameObject, transform.GetChild(0));
                    g.GetComponent <PropertyMenuBlockManager>().SetUp <bool>(propertyname, (bool)p.GetValue(configurationschema), generateAtRuntime, easyname);
                }
                if (p.PropertyType.IsEnum)
                {
                    g = GameObject.Instantiate(Resources.Load("UI/PropertyMenuBlockDropdown") as GameObject, transform.GetChild(0));
                    g.GetComponent <PropertyMenuBlockManager>().SetUp <System.Enum>(propertyname, (System.Enum)p.GetValue(configurationschema), generateAtRuntime, easyname);
                }

                blocks.Add(g.GetComponent <PropertyMenuBlockManager>());
            }
        }

        if (ThemePropertyName == "")
        {
            GameObject title = Instantiate(Resources.Load("UI/MenuApplicationTitle") as GameObject, transform);
            title.GetComponentInChildren <Text>().text = Application.productName;
        }
        else
        {
            GameObject title = Instantiate(Resources.Load("UI/MenuApplicationTitleAndTheme") as GameObject, transform);
            ThemeManager.StartUp();
            title.GetComponent <PropertyMenuBlockManager>().SetupTheme(ThemePropertyName, generateAtRuntime);
            theme = title.GetComponent <PropertyMenuBlockManager>();
            blocks.Add(theme);
        }

        GameObject PlayButton = Instantiate(Resources.Load("UI/PlayButton") as GameObject, transform);

        playgame = PlayButton.GetComponentInChildren <Button>();
        if (generateAtRuntime)
        {
            PlayButton.GetComponentInChildren <Button>().onClick.AddListener(delegate { PlayGame(); });
        }
    }
Пример #4
0
        private void Refresh()
        {
            if (!this._CheckNullReference())
            {
                return;
            }
            ((Component)this.MainPanelCloseBtn).get_gameObject().SetActive(true);
            this.SubPanel.SetActive(false);
            GameManager instanceDirect = MonoSingleton <GameManager> .GetInstanceDirect();

            if (UnityEngine.Object.op_Equality((UnityEngine.Object)instanceDirect, (UnityEngine.Object)null))
            {
                return;
            }
            this.mCurrentUnit = instanceDirect.Player.FindUnitDataByUniqueID((long)GlobalVars.SelectedUnitUniqueID);
            if (this.mCurrentUnit == null)
            {
                return;
            }
            GameUtility.DestroyGameObjects(this.mItems);
            GameUtility.DestroyGameObjects(this.mBoxs);
            this.mItems.Clear();
            this.mBoxs.Clear();
            DataSource.Bind <UnitData>(((Component)this).get_gameObject(), this.mCurrentUnit);
            GameParameter.UpdateAll(((Component)this).get_gameObject());
            string errMsg = (string)null;
            List <UnitData.TobiraConditioError> errors = (List <UnitData.TobiraConditioError>)null;
            bool flag1   = this.mCurrentUnit.CanUnlockTobira() && this.mCurrentUnit.MeetsTobiraConditions(TobiraParam.Category.START, out errors);
            int  condsLv = TobiraUtility.GetTobiraUnlockLevel(this.mCurrentUnit.UnitParam.iname);
            TobiraRecipeParam currentRecipe = this.GetCurrentRecipe();

            if (currentRecipe == null)
            {
                return;
            }
            DataSource.Bind <TobiraRecipeParam>(((Component)this).get_gameObject(), currentRecipe);
            if (errors.Count > 0)
            {
                errors.Find((Predicate <UnitData.TobiraConditioError>)(error =>
                {
                    if (error.Type != UnitData.TobiraConditioError.ErrorType.UnitLevel)
                    {
                        return(false);
                    }
                    errMsg = LocalizedText.Get("sys.TOBIRA_CONDS_ERR_UNIT_LV", new object[1]
                    {
                        (object)condsLv
                    });
                    return(true);
                }));
            }
            else if (currentRecipe.Cost > instanceDirect.Player.Gold)
            {
                errMsg = LocalizedText.Get("sys.GOLD_NOT_ENOUGH");
                flag1  = false;
            }
            int length = currentRecipe.Materials.Length;

            if (currentRecipe.UnitPieceNum > 0)
            {
                ++length;
            }
            if (currentRecipe.ElementNum > 0)
            {
                ++length;
            }
            if (currentRecipe.UnlockElementNum > 0)
            {
                ++length;
            }
            if (currentRecipe.UnlockBirthNum > 0)
            {
                ++length;
            }
            GridLayoutGroup component = (GridLayoutGroup)this.ItemSlotBox.GetComponent <GridLayoutGroup>();

            if (UnityEngine.Object.op_Equality((UnityEngine.Object)component, (UnityEngine.Object)null))
            {
                DebugUtility.LogWarning("UnitEvolutionWindow.cs => Refresh2():gridlayout is Not Component [GridLayoutGroup]!");
            }
            else
            {
                int num1 = length / component.get_constraintCount() + 1;
                for (int index = 0; index < num1; ++index)
                {
                    GameObject gameObject = (GameObject)UnityEngine.Object.Instantiate <GameObject>((M0)this.ItemSlotBox);
                    gameObject.get_transform().SetParent(this.ItemSlotRoot.get_transform(), false);
                    gameObject.SetActive(true);
                    this.mBoxs.Add(gameObject);
                }
                int num2   = 0;
                int index1 = 0;
                if (currentRecipe.UnitPieceNum > 0)
                {
                    GameObject gameObject = (GameObject)UnityEngine.Object.Instantiate <GameObject>((M0)this.ItemSlotTemplate);
                    gameObject.get_transform().SetParent(this.mBoxs[index1].get_transform(), false);
                    gameObject.SetActive(true);
                    this.mItems.Add(gameObject.get_gameObject());
                    ItemParam itemParam = instanceDirect.GetItemParam(this.mCurrentUnit.UnitParam.piece);
                    if (itemParam == null)
                    {
                        DebugUtility.LogWarning("UnitEvolutionWindow.cs => Refresh():item_param is Null References!");
                        return;
                    }
                    DataSource.Bind <ItemParam>(gameObject.get_gameObject(), itemParam);
                    DataSource.Bind <UnlockTobiraRecipe>(gameObject.get_gameObject(), new UnlockTobiraRecipe()
                    {
                        Amount         = instanceDirect.Player.GetItemAmount(itemParam.iname),
                        RequiredAmount = currentRecipe.UnitPieceNum,
                        Index          = num2
                    });
                    if (flag1 && currentRecipe.UnitPieceNum > instanceDirect.Player.GetItemAmount(this.mCurrentUnit.UnitParam.piece))
                    {
                        flag1  = false;
                        errMsg = LocalizedText.Get("sys.ITEM_NOT_ENOUGH");
                    }
                    ++num2;
                }
                int index2 = num2 / component.get_constraintCount();
                if (currentRecipe.ElementNum > 0)
                {
                    GameObject gameObject = (GameObject)UnityEngine.Object.Instantiate <GameObject>((M0)this.ItemSlotTemplate);
                    gameObject.get_transform().SetParent(this.mBoxs[index2].get_transform(), false);
                    gameObject.SetActive(true);
                    this.mItems.Add(gameObject.get_gameObject());
                    ItemParam elementPieceParam = this.mCurrentUnit.GetElementPieceParam();
                    if (elementPieceParam == null)
                    {
                        DebugUtility.LogWarning("UnitEvolutionWindow.cs => Refresh():item_param is Null References!");
                        return;
                    }
                    DataSource.Bind <ItemParam>(gameObject.get_gameObject(), elementPieceParam);
                    DataSource.Bind <UnlockTobiraRecipe>(gameObject.get_gameObject(), new UnlockTobiraRecipe()
                    {
                        Amount         = instanceDirect.Player.GetItemAmount(elementPieceParam.iname),
                        RequiredAmount = currentRecipe.ElementNum,
                        Index          = num2
                    });
                    if (flag1 && currentRecipe.ElementNum > instanceDirect.Player.GetItemAmount(elementPieceParam.iname))
                    {
                        flag1  = false;
                        errMsg = LocalizedText.Get("sys.ITEM_NOT_ENOUGH");
                    }
                    ++num2;
                }
                int index3 = num2 / component.get_constraintCount();
                if (currentRecipe.UnlockElementNum > 0)
                {
                    GameObject gameObject = (GameObject)UnityEngine.Object.Instantiate <GameObject>((M0)this.ItemSlotTemplate);
                    gameObject.get_transform().SetParent(this.mBoxs[index3].get_transform(), false);
                    gameObject.SetActive(true);
                    this.mItems.Add(gameObject.get_gameObject());
                    ItemParam itemParam = instanceDirect.GetItemParam(this.mCurrentUnit.GetUnlockTobiraElementID());
                    if (itemParam == null)
                    {
                        DebugUtility.LogWarning("UnitEvolutionWindow.cs => Refresh():item_param is Null References!");
                        return;
                    }
                    DataSource.Bind <ItemParam>(gameObject.get_gameObject(), itemParam);
                    DataSource.Bind <UnlockTobiraRecipe>(gameObject.get_gameObject(), new UnlockTobiraRecipe()
                    {
                        Amount         = instanceDirect.Player.GetItemAmount(itemParam.iname),
                        RequiredAmount = currentRecipe.UnlockElementNum,
                        Index          = num2
                    });
                    if (flag1 && currentRecipe.UnlockElementNum > instanceDirect.Player.GetItemAmount(this.mCurrentUnit.GetUnlockTobiraElementID()))
                    {
                        flag1  = false;
                        errMsg = LocalizedText.Get("sys.ITEM_NOT_ENOUGH");
                    }
                    ++num2;
                }
                int index4 = num2 / component.get_constraintCount();
                if (currentRecipe.UnlockBirthNum > 0)
                {
                    GameObject gameObject = (GameObject)UnityEngine.Object.Instantiate <GameObject>((M0)this.ItemSlotTemplate);
                    gameObject.get_transform().SetParent(this.mBoxs[index4].get_transform(), false);
                    gameObject.SetActive(true);
                    this.mItems.Add(gameObject.get_gameObject());
                    ItemParam itemParam = instanceDirect.GetItemParam(this.mCurrentUnit.GetUnlockTobiraBirthID());
                    if (itemParam == null)
                    {
                        DebugUtility.LogWarning("UnitEvolutionWindow.cs => Refresh():item_param is Null References!");
                        return;
                    }
                    DataSource.Bind <ItemParam>(gameObject.get_gameObject(), itemParam);
                    DataSource.Bind <UnlockTobiraRecipe>(gameObject.get_gameObject(), new UnlockTobiraRecipe()
                    {
                        Amount         = instanceDirect.Player.GetItemAmount(itemParam.iname),
                        RequiredAmount = currentRecipe.UnlockBirthNum,
                        Index          = num2
                    });
                    if (flag1 && currentRecipe.UnlockBirthNum > instanceDirect.Player.GetItemAmount(this.mCurrentUnit.GetUnlockTobiraBirthID()))
                    {
                        flag1  = false;
                        errMsg = LocalizedText.Get("sys.ITEM_NOT_ENOUGH");
                    }
                    ++num2;
                }
                foreach (TobiraRecipeMaterialParam material in currentRecipe.Materials)
                {
                    if (material != null && !string.IsNullOrEmpty(material.Iname))
                    {
                        int        index5     = num2 / component.get_constraintCount();
                        GameObject gameObject = (GameObject)UnityEngine.Object.Instantiate <GameObject>((M0)this.ItemSlotTemplate);
                        gameObject.get_transform().SetParent(this.mBoxs[index5].get_transform(), false);
                        gameObject.SetActive(true);
                        this.mItems.Add(gameObject.get_gameObject());
                        ItemParam itemParam = instanceDirect.GetItemParam(material.Iname);
                        if (itemParam == null)
                        {
                            DebugUtility.LogWarning("UnitEvolutionWindow.cs => Refresh():item_param is Null References!");
                            return;
                        }
                        DataSource.Bind <ItemParam>(gameObject.get_gameObject(), itemParam);
                        DataSource.Bind <UnlockTobiraRecipe>(gameObject.get_gameObject(), new UnlockTobiraRecipe()
                        {
                            Amount         = instanceDirect.Player.GetItemAmount(itemParam.iname),
                            RequiredAmount = material.Num,
                            Index          = num2
                        });
                        if (flag1 && material.Num > instanceDirect.Player.GetItemAmount(material.Iname))
                        {
                            flag1  = false;
                            errMsg = LocalizedText.Get("sys.ITEM_NOT_ENOUGH");
                        }
                        ++num2;
                    }
                }
                if (UnityEngine.Object.op_Inequality((UnityEngine.Object) this.HelpText, (UnityEngine.Object)null))
                {
                    bool flag2 = !string.IsNullOrEmpty(errMsg);
                    ((Component)this.HelpText).get_gameObject().SetActive(flag2);
                    if (flag2)
                    {
                        this.HelpText.set_text(errMsg);
                    }
                }
                if (!UnityEngine.Object.op_Inequality((UnityEngine.Object) this.UnlockTobiraButton, (UnityEngine.Object)null))
                {
                    return;
                }
                ((Selectable)this.UnlockTobiraButton).set_interactable(flag1);
            }
        }
Пример #5
0
        static void AddVerticalTableView(MenuCommand menuCommand)
        {
            GameObject verticalTableViewRoot = CreateUIElementRoot("vertical_tableview", menuCommand, s_ThickGUIElementSize);

            GameObject childTableRect = CreateUIObject("tablerect", verticalTableViewRoot);

            GameObject childContent = CreateUIObject("content", childTableRect);

            // Set RectTransform to stretch
            RectTransform rectTransformScrollSnapRoot = verticalTableViewRoot.GetComponent <RectTransform>();

            rectTransformScrollSnapRoot.anchorMin        = new Vector2(0.5f, 0.5f);
            rectTransformScrollSnapRoot.anchorMax        = new Vector2(0.5f, 0.5f);
            rectTransformScrollSnapRoot.pivot            = new Vector2(0.5f, 0.5f);
            rectTransformScrollSnapRoot.anchoredPosition = Vector2.zero;
            rectTransformScrollSnapRoot.sizeDelta        = new Vector2(300f, 600f);

            Image image = verticalTableViewRoot.AddComponent <Image>();

            image.sprite = AssetDatabase.GetBuiltinExtraResource <Sprite>(kStandardSpritePath);
            image.type   = Image.Type.Sliced;
            image.color  = new Color(1f, 1f, 1f, 0.392f);

            verticalTableViewRoot.AddComponent <RectMask2D>();

            ScrollRect sr = verticalTableViewRoot.AddComponent <ScrollRect>();

            sr.vertical   = true;
            sr.horizontal = false;

            RectTransform rectTransformRect = childTableRect.GetComponent <RectTransform>();

            rectTransformRect.anchorMin = Vector2.zero;
            rectTransformRect.anchorMax = new Vector2(1f, 1f);
            rectTransformRect.pivot     = new Vector2(0.5f, 0.5f);
            rectTransformRect.sizeDelta = Vector2.zero;

            sr.viewport = rectTransformRect;

            //Setup Content container
            RectTransform rectTransformContent = childContent.GetComponent <RectTransform>();

            rectTransformContent.anchorMin = new Vector2(0.5f, 1f);
            rectTransformContent.anchorMax = new Vector2(0.5f, 1f);
            rectTransformContent.pivot     = new Vector2(0.5f, 1f);
            rectTransformContent.sizeDelta = new Vector2(300f, 600f);

            GridLayoutGroup group = childContent.AddComponent <GridLayoutGroup>();

            group.cellSize        = new Vector2(300, 100);
            group.spacing         = new Vector2(0, 5);
            group.startCorner     = GridLayoutGroup.Corner.UpperLeft;
            group.startAxis       = GridLayoutGroup.Axis.Vertical;
            group.childAlignment  = TextAnchor.UpperCenter;
            group.constraint      = GridLayoutGroup.Constraint.FixedColumnCount;
            group.constraintCount = 1;
            group.enabled         = false;

            sr.content = rectTransformContent;

            //Need to add example child components like in the Asset (SJ)
            Selection.activeGameObject = verticalTableViewRoot;
        }
Пример #6
0
    //функція, яка створює підрівень в залежності від параметрів
    public void CreatePart(int x_count, int y_count, int time)
    {
        Clear();
        //визначаємо посилання на унікальний і типовий ігрові об'єкти за допомогою стартового масиву
        GameObject UniqueObj  = UniqueObjects[part - 1];
        GameObject ThesomeObj = ThesomeObjects[part - 1];

        //налаштовуємо заголовок вверху екрана і сітку для рошташування елементів
        Text HeaderText = HeaderObj.GetComponent <Text>();

        HeaderText.text = "Знайдіть зайвий елемент:";
        HeaderObj.SetActive(true);
        gamePanel = GameObject.FindGameObjectWithTag("GamePanel").GetComponent <RectTransform>();
        grid      = GameObject.FindGameObjectWithTag("GamePanel").GetComponent <GridLayoutGroup>();
        //в залежності від підрівня сітка також буде набувати інших параметрів
        grid.constraintCount = x_count;
        switch (x_count)
        {
        case 10:
            grid.cellSize = new Vector2(80, 80);
            grid.spacing  = new Vector2(15, 15);
            break;

        case 11:
            grid.cellSize = new Vector2(80, 80);
            grid.spacing  = new Vector2(10, 10);
            break;

        case 12:
            grid.cellSize = new Vector2(73, 73);
            grid.spacing  = new Vector2(10, 15);
            break;

        default:
            grid.cellSize = new Vector2(80, 80);
            grid.spacing  = new Vector2(10, 10);
            break;
        }
        //рандомно визначаємо позицію унікального елемента
        int unique_i = (int)(Random.value * 1000 % x_count);
        int unique_j = (int)(Random.value * 1000 % y_count);

        Objects = new List <GameObject>();
        //циклами проходимо по кожній клітинці компонента GridLayoutGroup
        for (int i = 0; i < x_count; i++)
        {
            for (int j = 0; j < y_count; j++)
            {
                //створюємо унікальний ігровий об'єкт і накладаємо на нього компонент, який зчитує дотики і кліки мишкою
                if ((i == unique_i) && (j == unique_j))
                {
                    Unique = Instantiate(UniqueObj, gamePanel.transform);
                    EventTrigger       trigger = Unique.GetComponent <EventTrigger>();
                    EventTrigger.Entry entry   = new EventTrigger.Entry();
                    entry.eventID = EventTriggerType.PointerDown;
                    entry.callback.AddListener((data) => { GoodAnswer((PointerEventData)data); });
                    trigger.triggers.Add(entry);
                    Objects.Add(Unique);
                }
                //аналогічно створюємо типовий об'єкти і додаємо все в список
                else
                {
                    GameObject         Thesome = Instantiate(ThesomeObj, gamePanel.transform);
                    EventTrigger       trigger = Thesome.GetComponent <EventTrigger>();
                    EventTrigger.Entry entry   = new EventTrigger.Entry();
                    entry.eventID = EventTriggerType.PointerDown;
                    entry.callback.AddListener((data) => { BadAnswer((PointerEventData)data); });
                    trigger.triggers.Add(entry);
                    Objects.Add(Thesome);
                }
            }
        }
        //активовуємо відлік таймера
        TimerCoroutine = StartCoroutine(Timer(time));
    }
 void Awake()
 {
     contentRect            = GetComponent <RectTransform>();
     contentGridLayoutGroup = GetComponent <GridLayoutGroup>();
     scrollRect             = GameObject.Find("Scroll View").GetComponent <ScrollRect>();
 }
Пример #8
0
 private void Awake()
 {
     _grid = GetComponent <GridLayoutGroup>();
 }
        GameObject CurrentEquipWindow(Transform Parent)
        {
            if (currentEquipWindow)
            {
                Object.Destroy(currentEquipWindow);
            }
            GridLayoutGroup CurrentEquips = Manager.GetPanel(Parent, new Vector2(400, 400), new Vector2(0, 150)).AddComponent <GridLayoutGroup>();

            CurrentEquips.transform.localScale = Vector3.one;
            CurrentEquips.padding = new RectOffset()
            {
                bottom = 15, top = 15, left = 15, right = 15
            };
            CurrentEquips.childAlignment = TextAnchor.MiddleCenter;
            CurrentEquips.spacing        = new Vector2(10, 10);

            if (Equipment.PrimaryWeapon)
            {
                ItemIconDisplay(CurrentEquips.transform, Equipment.PrimaryWeapon.Icon);
            }
            else
            {
                ItemIconDisplay(CurrentEquips.transform, null);
            }
            if (Equipment.SecondaryWeapon)
            {
                ItemIconDisplay(CurrentEquips.transform, Equipment.SecondaryWeapon.Icon);
            }
            else
            {
                ItemIconDisplay(CurrentEquips.transform, null);
            }
            if (Equipment.ProjectileWeopon)
            {
                ItemIconDisplay(CurrentEquips.transform, Equipment.ProjectileWeopon.Icon);
            }
            else
            {
                ItemIconDisplay(CurrentEquips.transform, null);
            }
            if (Equipment.Helmet)
            {
                ItemIconDisplay(CurrentEquips.transform, Equipment.Helmet.Icon);
            }
            else
            {
                ItemIconDisplay(CurrentEquips.transform, null);
            }
            if (Equipment.Arms)
            {
                ItemIconDisplay(CurrentEquips.transform, Equipment.Arms.Icon);
            }
            else
            {
                ItemIconDisplay(CurrentEquips.transform, null);
            }
            if (Equipment.Chest)
            {
                ItemIconDisplay(CurrentEquips.transform, Equipment.Chest.Icon);
            }
            else
            {
                ItemIconDisplay(CurrentEquips.transform, null);
            }
            if (Equipment.Legs)
            {
                ItemIconDisplay(CurrentEquips.transform, Equipment.Legs.Icon);
            }
            else
            {
                ItemIconDisplay(CurrentEquips.transform, null);
            }
            if (Equipment.Shield)
            {
                ItemIconDisplay(CurrentEquips.transform, Equipment.Shield.Icon);
            }
            else
            {
                ItemIconDisplay(CurrentEquips.transform, null);
            }
            if (Equipment.Signature)
            {
                ItemIconDisplay(CurrentEquips.transform, Equipment.Signature.Icon);
            }
            else
            {
                ItemIconDisplay(CurrentEquips.transform, null);
            }
            return(CurrentEquips.gameObject);
        }
Пример #10
0
 void Awake()
 {
     _Grid = GetComponent <GridLayoutGroup>();
 }
Пример #11
0
        // ---------[ INITIALIZATION ]---------
        public void Initialize()
        {
            Debug.Assert(itemPrefab != null);

            RectTransform prefabTransform = itemPrefab.GetComponent <RectTransform>();
            ModView       prefabView      = itemPrefab.GetComponent <ModView>();

            Debug.Assert(prefabTransform != null &&
                         prefabView != null,
                         "[mod.io] The ExplorerView.itemPrefab does not have the required "
                         + "ModBrowserItem, ModView, and RectTransform components.\n"
                         + "Please ensure these are all present.");

            // - initialize pages -
            foreach (Transform t in contentPane)
            {
                GameObject.Destroy(t.gameObject);
            }

            RecalculateColumnCountAndCellDimensions();

            // create mod pages
            currentPageContainer = new GameObject("Mod Page", typeof(RectTransform)).transform as RectTransform;
            currentPageContainer.SetParent(contentPane);
            currentPageContainer.anchorMin  = Vector2.zero;
            currentPageContainer.offsetMin  = Vector2.zero;
            currentPageContainer.anchorMax  = Vector2.one;
            currentPageContainer.offsetMax  = Vector2.zero;
            currentPageContainer.localScale = Vector2.one;
            currentPageContainer.pivot      = Vector2.zero;
            GridLayoutGroup layouter = currentPageContainer.gameObject.AddComponent <GridLayoutGroup>();

            ApplyGridLayoutValues(layouter);

            targetPageContainer = GameObject.Instantiate(currentPageContainer, contentPane).transform as RectTransform;
            targetPageContainer.gameObject.SetActive(false);


            // - nested views -
            if (tagFilterView != null)
            {
                tagFilterView.Initialize();

                tagFilterView.tagFilterAdded += (tag) =>
                {
                    filterTags.Add(tag);

                    if (tagFilterBar != null)
                    {
                        tagFilterBar.gameObject.SetActive(true);
                        tagFilterBar.DisplayTags(filterTags, m_tagCategories);
                    }

                    if (onFilterTagsChanged != null)
                    {
                        onFilterTagsChanged();
                    }
                };
                tagFilterView.tagFilterRemoved += RemoveTag;
            }

            if (tagFilterBar != null)
            {
                tagFilterBar.Initialize();
                tagFilterBar.gameObject.SetActive(filterTags.Count > 0);

                tagFilterBar.tagClicked += (display) =>
                {
                    RemoveTag(display.data.tagName);
                };
            }
        }
Пример #12
0
    //private IEnumerator CoInit()
    //{
    //    yield return null;
    //    _inited = true;
    //    _scrollRect = transform.GetComponentInParent<ScrollRect>();
    //    _isVertical = _scrollRect.vertical;
    //    //初始化_viewSpace
    //    RectTransform viewRectTrans = _scrollRect.viewport ? _scrollRect.viewport : (RectTransform)_scrollRect.transform;
    //    _viewSize = _isVertical ? viewRectTrans.rect.height : viewRectTrans.rect.width;

    //    _scrollRect.onValueChanged.AddListener(OnScroll);

    //    InitItemSpace();
    //    InitShowItem();
    //}

    /// <summary>
    ///  初始化渲染item的大小
    /// </summary>
    /// <param name="item"></param> 进行渲染的item
    public void InitItemSpace(params RectTransform[] renderItems)
    {
        if (renderItems != null && renderItems.Length != 0)
        {
            _renderItems = renderItems;
        }
        _layoutGroup = GetComponent <LayoutGroup>();
        if (_layoutGroup != null)
        {
            _initPadding = _layoutGroup.padding;
            //计算itemSpace
            if (_layoutGroup is HorizontalOrVerticalLayoutGroup)
            {
                _constraintCount = 1;
                HorizontalOrVerticalLayoutGroup hvLayout = (HorizontalOrVerticalLayoutGroup)_layoutGroup;
                _space = hvLayout.spacing;
                if (_isVertical)
                {
                    if (hvLayout.childControlHeight)//item拥有自己的layoutElement
                    {
                        LayoutElement element = _renderItems[0].GetComponent <LayoutElement>();
                        _itemSize = element.preferredHeight + hvLayout.spacing;
                    }
                    else
                    {
                        _itemSize = _renderItems[0].rect.height + hvLayout.spacing;
                    }
                }
                else
                {
                    if (hvLayout.childControlWidth)//item拥有自己的layoutElement
                    {
                        LayoutElement element = _renderItems[0].GetComponent <LayoutElement>();
                        _itemSize = element.preferredWidth + hvLayout.spacing;
                    }
                    else
                    {
                        _itemSize = _renderItems[0].rect.width + hvLayout.spacing;
                    }
                }
            }
            else if (_layoutGroup is GridLayoutGroup)
            {
                GridLayoutGroup gridLayout = (GridLayoutGroup)_layoutGroup;
                _constraintCount = gridLayout.constraintCount;
                if (_isVertical)
                {
                    _space    = gridLayout.spacing.y;
                    _itemSize = gridLayout.cellSize.y + _space;
                }
                else
                {
                    _space    = gridLayout.spacing.x;
                    _itemSize = gridLayout.cellSize.x + _space;
                }
            }
        }
        else
        {
            Debug.LogErrorFormat("<WrapContent> {0}:缺少Layout!", name);
        }
    }
 void OnValidate()
 {
     transform = (RectTransform)base.transform;
     grid      = GetComponent <GridLayoutGroup>();
     UpdateCellSize();
 }
 void Awake()
 {
     transform = (RectTransform)base.transform;
     grid      = GetComponent <GridLayoutGroup>();
 }
Пример #15
0
        public void Refresh(bool rebuild = true)
        {
            if (Application.isPlaying)
            {
                SetActiveLayout(true);
            }
            SymbolManager   symbolManager = slot.symbolManager;
            LineManager     lineManager   = slot.lineManager;
            SlotConfig      config        = slot.config;
            GridLayoutGroup reel          = slot.layoutReel;
            GridLayoutGroup row           = slot.layoutRow;

            if (rebuild)
            {
                slot.Validate();
                if (config.symbolsPerReel < config.totalRows)
                {
                    Debug.Log("[Error] Symbols per reel must be higher than total rows(including hidden rows).");
                    return;
                }
            }

            reel.cellSize = sizeSymbol;
            reel.spacing  = spacingSymbol;
            int px = (int)(spacingSymbol.x * 0.5f), py = (int)(spacingSymbol.y * 0.5f);

            reel.padding = new RectOffset(px, px, py, py);

            Vector2 spacing = sizeSymbol + spacingSymbol;
            float   width   = spacing.x * config.reelLength;
            float   height  = spacing.y * config.rows;

            row.cellSize = new Vector2(width, sizeSymbol.y + spacingSymbol.y);
            row.spacing  = Vector2.zero;

            slot.mainScreen.sizeDelta = new Vector2(width + paddingMainScreen.horizontal, height + paddingMainScreen.vertical);

            (reel.transform as RectTransform).anchoredPosition = (row.transform as RectTransform).anchoredPosition = new Vector2(paddingMainScreen.left, config.hiddenTopRows * spacing.y - paddingMainScreen.top);

            if (linkLineManagerTransformToMainScreen)
            {
                (lineManager.transform as RectTransform).sizeDelta = (slot.mainScreen.transform as RectTransform).sizeDelta;
                lineManager.transform.position = slot.mainScreen.transform.position;
            }

            if (rebuild)
            {
                SymbolMap map = symbolManager.GetSymbolMap();
                Util.DestroyChildren <Row>(row);
                for (int i = 0; i < config.totalRows; i++)
                {
                    GameObject.Instantiate(slot.skin.row).OnRefreshLayout(slot, i);
                }
                Util.DestroyChildren <Reel>(reel);
                for (int i = 0; i < config.reelLength; i++)
                {
                    GameObject.Instantiate(slot.skin.reel).OnRefreshLayout(slot, i);
                }
                slot.reels = reel.transform.GetComponentsInChildren <Reel>();
                slot.rows  = row.transform.GetComponentsInChildren <Row>();
                symbolManager.ApplySymbolMap(map);
                lineManager.OnRefreshLayout();
                slot.Validate();
            }
            else
            {
                //	DOTween.CompleteAll(true);
                foreach (Reel r in slot.reels)
                {
                    foreach (SymbolHolder h in r.holders)
                    {
                        h._rect.sizeDelta = sizeSymbol;
                    }
                    r.y = r.nextY = 0;
                    r.RefreshHolderPositions();
                }
            }

            if (Application.isPlaying)
            {
                SetActiveLayout(false);
            }
        }
        // Do we need to add a name tag?
        Image ItemIconDisplay(Transform Parent, Sprite image)
        {
            Image temp = new GameObject().AddComponent <Image>();

            temp.transform.SetParent(Parent, false);
            temp.sprite = image;
            if (!image)
            {
                temp.color = new Color()
                {
                    a = 0.0f
                }
            }
            ;
            return(temp);
        }

        ItemType DisplayItems = (ItemType)1;
        GameObject itemPanel {
            get; set;
        }
        GameObject CreateItemPanel()
        {
            GameObject MainPanel = Manager.GetPanel(MenuPanelParent.transform, new Vector2(1400, 300), new Vector2(0, 150));

            MainPanel.transform.SetSiblingIndex(1);
            VerticalLayoutGroup VLG = MainPanel.AddComponent <VerticalLayoutGroup>();

            MainPanel.name = "Item Window";
            VLG.padding    = new RectOffset()
            {
                bottom = 20, top = 20, left = 20, right = 20
            };
            VLG.childAlignment         = TextAnchor.UpperCenter;
            VLG.childControlHeight     = true; VLG.childControlWidth = true;
            VLG.childForceExpandHeight = false; VLG.childForceExpandWidth = true;

            Text titleGO = Manager.TextBox(MainPanel.transform, new Vector2(400, 50)).GetComponent <Text>();

            titleGO.alignment = TextAnchor.MiddleCenter;
            titleGO.text      = "Inventory";
            titleGO.fontSize  = 24;
            titleGO.name      = "Inventory Title TextBox";
            HorizontalLayoutGroup InventoryPanel = Manager.GetPanel(MainPanel.transform, new Vector2(400, 900), new Vector2(0, 150)).AddComponent <HorizontalLayoutGroup>();

            InventoryPanel.name = " Control Display Buttons";
            InventoryPanel.childControlHeight     = false;
            InventoryPanel.childForceExpandHeight = false;
            MainPanel.name = "Items Window";

            for (int i = 1; i < 7; i++)
            {
                int    test = i;
                Button Temp = Manager.UIButton(InventoryPanel.transform, ((ItemType)i).ToString());
                Temp.name = ((ItemType)i).ToString();
                Temp.onClick.AddListener(() => {
                    DisplayItems        = (ItemType)test;
                    itemsDisplayerPanel = ItemsDisplayPanel(MainPanel.transform, Inventory, DisplayItems);
                });
            }
            itemsDisplayerPanel = ItemsDisplayPanel(MainPanel.transform, Inventory, DisplayItems);

            return(MainPanel);
        }

        GameObject itemsDisplayerPanel {
            get; set;
        }
        GameObject ItemsDisplayPanel(Transform Parent, InventoryBase inventory, ItemType Type)
        {
            if (itemsDisplayerPanel)
            {
                Object.Destroy(itemsDisplayerPanel);
            }

            GridLayoutGroup Main = Manager.GetPanel(Parent, new Vector2(1400, 300), new Vector2(0, 150)).AddComponent <GridLayoutGroup>();

            Main.padding = new RectOffset()
            {
                bottom = 20, top = 20, left = 20, right = 20
            };
            Main.spacing = new Vector2(20, 20);
            for (int i = 0; i < inventory.ItemsInInventory.Count - 1; i++)
            {
                ItemSlot Slot    = inventory.ItemsInInventory[i];
                int      IndexOf = i;
                if (Slot.Item.Type == Type)
                {
                    Button temp = ItemButton(Main.transform, Slot);
                    temp.onClick.AddListener(() =>
                    {
                        GameObject pop = PopUpItemPanel(temp.GetComponent <RectTransform>().anchoredPosition
                                                        + new Vector2(575, -175)
                                                        , Slot, IndexOf);
                        // pop.AddComponent<PopUpMouseControl>();
                    });
                }
            }

            return(Main.gameObject);
        }

        Button ItemButton(Transform Parent, ItemSlot Slot)
        {
            Button temp = Manager.UIButton(Parent, Slot.Item.ItemName);

            temp.name = Slot.Item.ItemName;
            Text texttemp = temp.GetComponentInChildren <Text>();

            texttemp.alignment = TextAnchor.LowerCenter;
            if (Slot.Item.Stackable)
            {
                texttemp.text += Slot.Count;
            }
            temp.GetComponentInChildren <Text>().alignment = TextAnchor.LowerCenter;
            temp.GetComponent <Image>().sprite             = Slot.Item.Icon;


            return(temp);
        }

        GameObject PopUpItemPanel(Vector2 Pos, ItemSlot Slot, int IndexOf)
        {
            GameObject            PopUp = Manager.GetPanel(Manager.UICanvas().transform, new Vector2(300, 300), Pos);
            HorizontalLayoutGroup group = PopUp.AddComponent <HorizontalLayoutGroup>();

            PopUp.AddComponent <PopUpMouseControl>();

            group.childControlWidth = false;

            Text info = Manager.TextBox(PopUp.transform, new Vector2(150, 300));

            info.text  = Slot.Item.ItemName + "\n";
            info.text += Slot.Item.Description;

            VerticalLayoutGroup ButtonPanel = Manager.GetPanel(PopUp.transform, new Vector2(150, 300), Pos).AddComponent <VerticalLayoutGroup>();

            switch (Slot.Item.Type)
            {
            case ItemType.General:
                Button use = Manager.UIButton(ButtonPanel.transform, "Use Item");
                use.onClick.AddListener(() =>
                {
                    RecoveryItemSO temp = (RecoveryItemSO)Slot.Item;
                    temp.Use(Inventory, IndexOf, Character);

                    itemsDisplayerPanel = ItemsDisplayPanel(itemPanel.transform, Inventory, DisplayItems);
                    Object.Destroy(PopUp);
                });
                info.text += "\nQuantity: " + Slot.Count;
                break;

            case ItemType.Armor:
            case ItemType.Weapon:
                Button Equip = Manager.UIButton(ButtonPanel.transform, "Equip");
                Equip.onClick.AddListener(() =>
                {
                    switch (Slot.Item.Type)
                    {
                    case ItemType.Armor:
                        ArmorSO Armor = (ArmorSO)Slot.Item;
                        Armor.EquipItem(Inventory, Equipment, IndexOf, Character);
                        break;

                    case ItemType.Weapon:
                        WeaponSO weapon = (WeaponSO)Slot.Item;
                        weapon.EquipItem(Inventory, Equipment, IndexOf, Character);

                        break;
                    }
                    itemsDisplayerPanel = ItemsDisplayPanel(itemPanel.transform, Inventory, DisplayItems);
                    playerStats         = CreatePlayerPanel();
                    Object.Destroy(PopUp);
                });
                Button Mod = Manager.UIButton(ButtonPanel.transform, "Modify");
                Mod.onClick.AddListener(() => Debug.LogWarning("Implentation to be added once Skill/Magic system designed"));
                Button Dismantle = Manager.UIButton(ButtonPanel.transform, "Dismantle");

                break;

            case ItemType.Quest:
                Button View = Manager.UIButton(ButtonPanel.transform, "View Item");

                break;

            case ItemType.Blueprint_Recipes:
                break;
            }
            if (Slot.Item.Type != ItemType.Quest)
            {
                Button Drop = Manager.UIButton(ButtonPanel.transform, "Drop");
                Drop.onClick.AddListener(() => {
                    Slot.Item.RemoveFromInventory(Inventory, IndexOf);
                    Object.Destroy(PopUp);
                });
            }
            // Button Cancel = Manager.UIButton(ButtonPanel.transform, "Cancel");

            return(PopUp);
        }
    }
Пример #17
0
 void Awake()
 {
     Load();
     scores = GetComponentInChildren <GridLayoutGroup>();
     LoadRankingUI();
 }
Пример #18
0
 private void Awake()
 {
     grid = GetComponentInChildren <GridLayoutGroup>();
 }
Пример #19
0
 private void OnEnable()
 {
     //Debug.Log("ImageTextEditor");
     t     = target as ImageText;
     group = t.gameObject.GetComponent <GridLayoutGroup>();
 }
Пример #20
0
    //刷新UI信息
    public void RefreshUI()
    {
        if (GetWindowState() == false)
        {
            return;
        }

        PlayerData playerData = GameRoot.instance.playerData;
        int        fight      = PECommon.GetFightProps(playerData);
        int        power      = PECommon.GetPowerLimit(playerData.lv);

        //为UI赋值
        SetText(txtFight, fight);
        SetText(txtPower, new StringBuilder("体力:").Append(playerData.power).Append("/").Append(power).ToString());
        imgPowerPrg.fillAmount = playerData.power * 1.0f / power;
        SetText(txtLevel, playerData.lv);
        SetText(txtName, playerData.name);

        #region ExpPrg

        //经验值条自适应
        GridLayoutGroup grid        = expPrgTrans.GetComponent <GridLayoutGroup>();
        float           globalScale = 1.0f * Constants.ScreenStandardHeight / Screen.height;
        float           screenWidth = Screen.width * globalScale;
        float           width       = (screenWidth - 180) / 10;

        grid.cellSize = new Vector2(width, 7);

        //计算经验值百分比
        int expProVal = (int)(playerData.exp * 1.0f / PECommon.GetExpUpValByLv(playerData.lv) * 100);
        SetText(txtExpPrg, expProVal + "%");

        //填充经验值进度条
        int index = expProVal / 10;
        for (int i = 0; i < expPrgTrans.childCount; i++)
        {
            Image img = expPrgTrans.GetChild(i).GetComponent <Image>();
            if (i < index)
            {
                img.fillAmount = 1;
            }
            else if (i == index)
            {
                img.fillAmount = expProVal % 10 * 1.0f / 10;
            }
            else
            {
                img.fillAmount = 0;
            }
        }

        #endregion

        m_curTaskData = resSvc.GetGuideCfgData(playerData.guideId);
        if (m_curTaskData != null)
        {
            SetGuideBtnIcon(m_curTaskData.npcID);
        }
        else
        {
            SetGuideBtnIcon(-1);
        }
    }
 void Start()
 {
     gridLayoutGroup    = gameObject.GetComponent <GridLayoutGroup>();
     explanationHashSet = new HashSet <string>();
 }
Пример #22
0
    /// <summary>
    /// Instantiate match results prefabs in results panel
    /// </summary>
    private void SetResultsPanel()
    {
        GridLayoutGroup layoutGroup = contentResulstPanel.GetComponent <GridLayoutGroup>();

        switch (tourInfo.teamsAmount)
        {
        case 32:
            layoutGroup.constraintCount = 17;
            break;

        case 16:
            layoutGroup.constraintCount = 9;
            break;

        case 12:
            layoutGroup.constraintCount = 7;
            break;

        case 24:
            layoutGroup.constraintCount = 13;
            break;
        }
        int i = 0;

        while (i < tourInfo.groupPhaseMatches.Count)
        {
            if (tourInfo.groupPhaseMatches[i].played)
            {
                if (i == 0)
                {
                    Text txt = Instantiate(roundTextPrefab);
                    txt.text = "Round 1";
                    txt.gameObject.transform.SetParent(contentResulstPanel);
                }

                if (i > 0 && tourInfo.groupPhaseMatches[i].matchNumber != tourInfo.groupPhaseMatches[i - 1].matchNumber)
                {
                    Text txt = Instantiate(roundTextPrefab);
                    int  r   = tourInfo.groupPhaseMatches[i].matchNumber + 1;
                    txt.text = "Round " + r;
                    txt.gameObject.transform.SetParent(contentResulstPanel);
                }

                GameObject mR = matchResultPrefab;
                //Get local team
                Team teamInfo = Resources.Load <Team>("Teams/" + tourInfo.groupPhaseMatches[i].localTeam.teamName + "/" + tourInfo.groupPhaseMatches[i].localTeam.teamName);
                //Set local team flag
                mR.transform.GetChild(0).GetComponent <Image>().sprite = teamInfo.flag;
                //Set local name
                mR.transform.GetChild(1).GetComponent <Text>().text = teamInfo.teamName;
                //Set local goals
                mR.transform.GetChild(2).GetComponent <Text>().text = tourInfo.groupPhaseMatches[i].localGoals.ToString();

                //Set knockoutText
                if (tourInfo.groupPhaseMatches[i].localGoals == 5 || tourInfo.groupPhaseMatches[i].visitGoals == 5)
                {
                    mR.transform.GetChild(4).GetComponent <Text>().text = "Knockout";
                }
                else
                {
                    mR.transform.GetChild(4).GetComponent <Text>().text = "";
                }

                //Get visit team
                teamInfo = Resources.Load <Team>("Teams/" + tourInfo.groupPhaseMatches[i].visitTeam.teamName + "/" + tourInfo.groupPhaseMatches[i].visitTeam.teamName);
                //Set visit team flag
                mR.transform.GetChild(7).GetComponent <Image>().sprite = teamInfo.flag;
                //Set visit name
                mR.transform.GetChild(6).GetComponent <Text>().text = teamInfo.teamName;
                //Set visit goals
                mR.transform.GetChild(5).GetComponent <Text>().text = tourInfo.groupPhaseMatches[i].visitGoals.ToString();

                //Instiate the object as child of content's results panel
                Instantiate(mR).transform.SetParent(contentResulstPanel);

                //Increase the size of the content's panel
                // contentResulstPanel.rect = new Rect()

                i++;
            }
            else
            {
                break;
            }
        }
        ;

        //No results yet
        if (i == 0)
        {
            Text txt = Instantiate(roundTextPrefab);
            txt.text = "No results";
            txt.gameObject.transform.SetParent(contentResulstPanel);
        }
    }
Пример #23
0
        public Blend(DollMaker dm) : base(dm)
        {
            dm.mainControls.RegisterTab("Blend", moduleUI);
            CreateModuleButton("Add Appearances").button.onClick.AddListener(() =>
            {
                SuperController.singleton.editModeToggle.isOn = true;
                SuperController.singleton.ShowMainHUD();

                SuperController.singleton.GetDirectoryPathDialog((string dir) =>
                {
                    if (dir == null || !(dir != string.Empty))
                    {
                        return;
                    }

                    //  have load dialog work both inside and outside folder
                    try
                    {
                        PerformLoadOnPath(dir);
                    }
                    catch
                    {
                        string folderName = "\\" + dir.Substring(dir.LastIndexOf('\\') + 1) + "\\";
                        dir = dir.Replace(folderName, "\\");
                        PerformLoadOnPath(dir);
                    }
                }, SuperController.singleton.savesDir + "Person" + "\\appearance");
            });

            appearancesLayout = ui.CreateGridLayout(1000, 500, moduleUI.transform);
            appearancesLayout.transform.localPosition = new Vector3(0, -600, 0);
            appearancesLayout.GetComponent <RectTransform>().pivot = new Vector2(0, 0);
            appearancesLayout.childAlignment  = TextAnchor.UpperLeft;
            appearancesLayout.constraint      = GridLayoutGroup.Constraint.FixedColumnCount;
            appearancesLayout.constraintCount = 3;
            appearancesLayout.cellSize        = new Vector2(Mathf.FloorToInt(1000 / 3), 80);

            SuperController.singleton.currentSaveDir = SuperController.singleton.currentLoadDir;
            JSONClass initialAppearance = SuperController.singleton.GetSaveJSON(atom, false, true).AsObject["atoms"].AsArray[0].AsObject;

            AddAppearance(initialAppearance, "Current", 1);

            CreateModuleButton("Clear List").button.onClick.AddListener(() =>
            {
                sliders.ForEach((slider) =>
                {
                    GameObject.Destroy(slider.gameObject);
                });
                sliders.Clear();
                appearances.Clear();
                computedWeightedMorphs.Clear();

                initialAppearance = SuperController.singleton.GetSaveJSON(atom, false, true).AsObject["atoms"].AsArray[0].AsObject;
                AddAppearance(initialAppearance, "Current", 1);
            });

            CreateModuleButton("Randomize").button.onClick.AddListener(() =>
            {
                sliders.ForEach((slider) =>
                {
                    slider.slider.value = UnityEngine.Random.Range(0.0f, 1.0f);
                });
            });

            CreateModuleButton("Average").button.onClick.AddListener(() =>
            {
                sliders.ForEach((slider) =>
                {
                    slider.slider.value = 0.5f;
                });
            });


            JSONStorable         geometry  = atom.GetStorableByID("geometry");
            DAZCharacterSelector character = geometry as DAZCharacterSelector;

            morphControl = character.morphsControlUI;
        }
Пример #24
0
    void initCard(int row, int col)
    {
        //1.加载卡牌图片
        Debug.LogError("row:" + row + " col:" + col);
        Sprite[] sps = Resources.LoadAll <Sprite>("");
        //2.计算需要加载卡牌的数量
        int totalCount = row * col / 2;

        Debug.LogError("计划加载:" + totalCount);
        //3.计算随机加载卡牌的索引
        List <Sprite> spsList = new List <Sprite>();

        for (int i = 0; i < sps.Length; i++)
        {
            spsList.Add((sps[i]));
        }

        List <Sprite> needShowCardList = new List <Sprite>();

        while (totalCount > 0)
        {
            int randomIndex = Random.Range(0, spsList.Count);
            needShowCardList.Add(spsList[randomIndex]);
            needShowCardList.Add(spsList[randomIndex]);
            spsList.RemoveAt(randomIndex);
            totalCount--;
        }

        for (int i = 0; i < needShowCardList.Count; i++)
        {
            // Debug.LogError(needShowCardList[i].name);
        }

        //4.显示卡牌到UI上
        Transform contentRoot = panelCard.Find("Panel");
        // int maxCount = Mathf.Max(contentRoot.childCount, needShowCardList.Count);
        int        maxCount   = Mathf.Max(contentRoot.childCount, needShowCardList.Count);
        GameObject itemPrefab = contentRoot.GetChild(0).gameObject;

        Debug.LogError("maxCount:" + maxCount);

        for (int i = 0; i < maxCount; i++)
        {
            GameObject itemObject = null;
            if (i < contentRoot.childCount)
            {
                itemObject = contentRoot.GetChild(i).gameObject;
            }
            else
            {
                itemObject = GameObject.Instantiate <GameObject>(itemPrefab);
                itemObject.transform.SetParent(contentRoot, false);
            }
            Debug.LogError("index:" + i);
            itemObject.transform.Find("card_front").GetComponent <Image>().sprite = needShowCardList[i];
            CardFlipAnim cardFlipAnim = itemObject.GetComponent <CardFlipAnim>();
            cardFlipAnim.setDefaultStatus();
        }

        GridLayoutGroup glg = contentRoot.GetComponent <GridLayoutGroup>();

        float panelWidth  = col * glg.cellSize.x + glg.padding.left + glg.padding.right + (col - 1) * glg.spacing.x;
        float panelHeight = row * glg.cellSize.y + glg.padding.top + glg.padding.bottom + (row - 1) * glg.spacing.y;

        contentRoot.GetComponent <RectTransform>().sizeDelta = new Vector2(panelWidth, panelHeight);
    }
Пример #25
0
    IEnumerator InitChildren()
    {
        yield return(0);

        if (!hasInit)
        {
            //获取Grid的宽度;
            rectTransform = GetComponent <RectTransform>();

            gridLayoutGroup           = GetComponent <GridLayoutGroup>();
            gridLayoutGroup.enabled   = false;
            contentSizeFitter         = GetComponent <ContentSizeFitter>();
            contentSizeFitter.enabled = false;

            gridLayoutPos  = rectTransform.anchoredPosition;
            gridLayoutSize = rectTransform.sizeDelta;

            //注册ScrollRect滚动回调;
            scrollRect = transform.parent.parent.GetComponent <ScrollRect>();
            scrollRect.onValueChanged.AddListener((data) => { ScrollCallback(data); });

            //获取所有child anchoredPosition 以及 SiblingIndex;
            for (int index = 0; index < transform.childCount; index++)
            {
                Transform     child          = transform.GetChild(index);
                RectTransform childRectTrans = child.GetComponent <RectTransform>();
                childsAnchoredPosition.Add(child, childRectTrans.anchoredPosition);

                childsSiblingIndex.Add(child, child.GetSiblingIndex());
            }
        }
        else
        {
            rectTransform.anchoredPosition = gridLayoutPos;
            rectTransform.sizeDelta        = gridLayoutSize;

            children.Clear();

            realIndex = -1;

            //children重新设置上下顺序;
            foreach (var info in childsSiblingIndex)
            {
                info.Key.SetSiblingIndex(info.Value);
            }

            //children重新设置anchoredPosition;
            for (int index = 0; index < transform.childCount; index++)
            {
                Transform child = transform.GetChild(index);

                RectTransform childRectTrans = child.GetComponent <RectTransform>();
                if (childsAnchoredPosition.ContainsKey(child))
                {
                    childRectTrans.anchoredPosition = childsAnchoredPosition[child];
                }
                else
                {
                    Debug.LogError("childsAnchoredPosition no contain " + child.name);
                }
            }
        }

        //获取所有child;
        for (int index = 0; index < transform.childCount; index++)
        {
            Transform trans = transform.GetChild(index);
            trans.gameObject.SetActive(true);

            children.Add(transform.GetChild(index).GetComponent <RectTransform>());

            //初始化前面几个;
            UpdateChildrenCallback(children.Count - 1, transform.GetChild(index));
        }

        startPosition = rectTransform.anchoredPosition;

        realIndex = children.Count - 1;

        hasInit = true;

        //如果需要显示的个数小于设定的个数;
        for (int index = 0; index < minAmount; index++)
        {
            children[index].gameObject.SetActive(index < amount);
        }

        if (gridLayoutGroup.constraint == GridLayoutGroup.Constraint.FixedColumnCount)
        {
            //如果小了一行,则需要把GridLayout的高度减去一行的高度;
            int row = (minAmount - amount) / gridLayoutGroup.constraintCount;
            if (row > 0)
            {
                rectTransform.sizeDelta -= new Vector2(0, (gridLayoutGroup.cellSize.y + gridLayoutGroup.spacing.y) * row);
            }
        }
        else
        {
            //如果小了一列,则需要把GridLayout的宽度减去一列的宽度;
            int column = (minAmount - amount) / gridLayoutGroup.constraintCount;
            if (column > 0)
            {
                rectTransform.sizeDelta -= new Vector2((gridLayoutGroup.cellSize.x + gridLayoutGroup.spacing.x) * column, 0);
            }
        }
    }
Пример #26
0
        /// <summary>
        /// Create the dropdown menu from scratch.
        /// </summary>
        /// <param name="parent">The canvas parent</param>
        /// <returns>Menu Object</returns>
        static public GameObject createDropdown(GameObject parent)
        {
            // Create head first, some variables may be filled in later.
            GameObject head = new GameObject("Button Dropdown");

            GameObjectUtility.SetParentAndAlign(head, parent);
            Selection.activeObject = head;
            head.AddComponent <RectTransform>();
            DropdownManager manager = head.AddComponent <DropdownManager>();

            Undo.RegisterCreatedObjectUndo(head, "Create " + head.name);

            // Create backdrop
            GameObject backdrop = new GameObject("Backdrop");

            GameObjectUtility.SetParentAndAlign(backdrop, head);
            RectTransform itemTransform = backdrop.AddComponent <RectTransform>();

            itemTransform.anchorMin     = new Vector2(0, 1);
            itemTransform.anchorMax     = new Vector2(0, 1);
            itemTransform.pivot         = new Vector2(0, 1);
            itemTransform.localPosition = new Vector2(-55f, 50f);
            backdrop.AddComponent <CanvasRenderer>();
            Image backdropImage = backdrop.AddComponent <Image>();

            backdropImage.sprite = AssetDatabase.GetBuiltinExtraResource <Sprite>("UI/Skin/UISprite.psd");
            backdropImage.type   = Image.Type.Sliced;
            backdrop.SetActive(false);
            manager.backdropObject = backdrop;
            Undo.RegisterCompleteObjectUndo(backdrop, "Create " + backdrop.name);

            // Create open button
            GameObject button = createButton(head, true, true);

            button.name = "Open Button";
            Button function = button.GetComponent <Button>();

            UnityEventTools.AddPersistentListener(function.onClick, manager.Dropdown);
            GameObject buttonText = createText(button, "Open");

            // Create submanager
            GameObject subManager = new GameObject("Manager");

            GameObjectUtility.SetParentAndAlign(subManager, head);
            itemTransform               = subManager.AddComponent <RectTransform>();
            itemTransform.anchorMin     = new Vector2(0.5f, 1);
            itemTransform.anchorMax     = new Vector2(0.5f, 1);
            itemTransform.pivot         = new Vector2(0.5f, 1);
            itemTransform.localPosition = new Vector2(0f, 45f);
            GridLayoutGroup layout = subManager.AddComponent <GridLayoutGroup>();

            layout.cellSize          = new Vector2(100, 50);
            layout.childAlignment    = TextAnchor.UpperCenter;
            layout.spacing           = new Vector2(5, 5);
            manager.subButtonManager = subManager;
            Undo.RegisterCompleteObjectUndo(subManager, "Create " + subManager.name);

            // Fill submanager
            button      = createButton(subManager, true, false);
            button.name = "Close Button";
            function    = button.GetComponent <Button>();
            UnityEventTools.AddPersistentListener(function.onClick, manager.Dropdown);
            buttonText = createText(button, "Close");
            button.SetActive(false);
            for (int i = 0; i < 2; i++)
            {
                button      = createButton(subManager, false, false);
                button.name = "Option " + (i + 1);
                buttonText  = createText(button, "Option " + (i + 1));
                button.SetActive(false);
            }

            manager.enabled = true;
            return(head);
        }
        protected override void Awake()
        {
            base.Awake();

            if (m_virtualContent == null)
            {
                return;
            }

            m_virtualContentTransformChangeListener = m_virtualContent.GetComponent <RectTransformChangeListener>();
            m_virtualContentTransformChangeListener.RectTransformChanged += OnVirtualContentTransformChaged;

            UpdateVirtualContentPosition();

            if (m_useGrid)
            {
                LayoutGroup layoutGroup = m_virtualContent.GetComponent <LayoutGroup>();
                if (layoutGroup != null && !(layoutGroup is GridLayoutGroup))
                {
                    DestroyImmediate(layoutGroup);
                }

                GridLayoutGroup gridLayout = m_virtualContent.GetComponent <GridLayoutGroup>();
                if (gridLayout == null)
                {
                    gridLayout = m_virtualContent.gameObject.AddComponent <GridLayoutGroup>();
                }

                gridLayout.cellSize       = ContainerPrefab.rect.size;
                gridLayout.childAlignment = TextAnchor.UpperLeft;
                gridLayout.startCorner    = GridLayoutGroup.Corner.UpperLeft;
                gridLayout.spacing        = m_gridSpacing;
                if (m_mode == VirtualizingMode.Vertical)
                {
                    gridLayout.startAxis  = GridLayoutGroup.Axis.Horizontal;
                    gridLayout.constraint = GridLayoutGroup.Constraint.FixedColumnCount;
                }
                else
                {
                    gridLayout.startAxis  = GridLayoutGroup.Axis.Vertical;
                    gridLayout.constraint = GridLayoutGroup.Constraint.FixedRowCount;
                }
                m_gridLayoutGroup = gridLayout;
            }
            else
            {
                if (m_mode == VirtualizingMode.Horizontal)
                {
                    //In horizontal mode we destroy VerticalLayoutGroup or GridLayoutGroup if exists

                    LayoutGroup layoutGroup = m_virtualContent.GetComponent <LayoutGroup>();
                    if (layoutGroup != null && !(layoutGroup is HorizontalLayoutGroup))
                    {
                        DestroyImmediate(layoutGroup);
                    }

                    // Create HorizontalLayoutGroup if does not exists

                    HorizontalLayoutGroup horizontalLayout = m_virtualContent.GetComponent <HorizontalLayoutGroup>();
                    if (horizontalLayout == null)
                    {
                        horizontalLayout = m_virtualContent.gameObject.AddComponent <HorizontalLayoutGroup>();
                    }

                    // Setup HorizontalLayoutGroup behavior to arrange ui containers correctly

                    horizontalLayout.childControlHeight    = true;
                    horizontalLayout.childControlWidth     = false;
                    horizontalLayout.childForceExpandWidth = false;
                }
                else
                {
                    //In horizontal mode we destroy HorizontalLayoutGroup or GridLayoutGroup if exists

                    LayoutGroup layoutGroup = m_virtualContent.GetComponent <LayoutGroup>();
                    if (layoutGroup != null && !(layoutGroup is VerticalLayoutGroup))
                    {
                        DestroyImmediate(layoutGroup);
                    }

                    // Create VerticalLayoutGroup if does not exists

                    VerticalLayoutGroup verticalLayout = m_virtualContent.GetComponent <VerticalLayoutGroup>();
                    if (verticalLayout == null)
                    {
                        verticalLayout = m_virtualContent.gameObject.AddComponent <VerticalLayoutGroup>();
                    }

                    // Setup VerticalLayoutGroup behavior to arrange ui containers correctly

                    verticalLayout.childControlWidth      = true;
                    verticalLayout.childControlHeight     = false;
                    verticalLayout.childForceExpandHeight = false;
                }
            }

            // Set ScrollSensitivity to be exactly the same as ContainerSize

            scrollSensitivity = ContainerSize;// * ContainersPerGroup;
        }
Пример #28
0
        private void Reset()
        {
            _childrenPos.Clear();
            float spacing = 0f;

            //根据dir计算坐标,Horizontal:存x,Vertical:存y
            switch (Dir)
            {
            case ScrollDir.Horizontal:
                if (_layoutGroup is HorizontalLayoutGroup)
                {
                    float childPosX = _scrollView.GetComponent <RectTransform>().rect.width * 0.5f - GetChildItemWidth(0) * 0.5f;
                    spacing = (_layoutGroup as HorizontalLayoutGroup).spacing;
                    _childrenPos.Add(childPosX);
                    for (int i = 1; i < _content.childCount; i++)
                    {
                        childPosX -= GetChildItemWidth(i) * 0.5f + GetChildItemWidth(i - 1) * 0.5f + spacing;
                        _childrenPos.Add(childPosX);
                    }
                }
                else if (_layoutGroup is GridLayoutGroup)
                {
                    GridLayoutGroup grid      = _layoutGroup as GridLayoutGroup;
                    float           childPosX = _scrollView.GetComponent <RectTransform>().rect.width * 0.5f - grid.cellSize.x * 0.5f;
                    _childrenPos.Add(childPosX);
                    for (int i = 0; i < _content.childCount - 1; i++)
                    {
                        childPosX -= grid.cellSize.x + grid.spacing.x;
                        _childrenPos.Add(childPosX);
                    }
                }
                else
                {
                    Debug.LogError("Horizontal ScrollView is using VerticalLayoutGroup");
                }
                FindClosestChildPos(_content.localPosition.x, out _curCenterChildIndex);
                break;

            case ScrollDir.Vertical:
                if (_layoutGroup is VerticalLayoutGroup)
                {
                    float childPosY = -_scrollView.GetComponent <RectTransform>().rect.height * 0.5f + GetChildItemHeight(0) * 0.5f;
                    spacing = (_layoutGroup as VerticalLayoutGroup).spacing;
                    _childrenPos.Add(childPosY);
                    for (int i = 1; i < _content.childCount; i++)
                    {
                        childPosY += GetChildItemHeight(i) * 0.5f + GetChildItemHeight(i - 1) * 0.5f + spacing;
                        _childrenPos.Add(childPosY);
                    }
                }
                else if (_layoutGroup is GridLayoutGroup)
                {
                    GridLayoutGroup grid      = _layoutGroup as GridLayoutGroup;
                    float           childPosY = -_scrollView.GetComponent <RectTransform>().rect.height * 0.5f + grid.cellSize.y * 0.5f;
                    _childrenPos.Add(childPosY);
                    for (int i = 1; i < _content.childCount; i++)
                    {
                        childPosY += grid.cellSize.y + grid.spacing.y;
                        _childrenPos.Add(childPosY);
                    }
                }
                else
                {
                    Debug.LogError("Vertical ScrollView is using HorizontalLayoutGroup");
                }
                break;
            }
            SetStartPosition(_startPositionIndex);
        }
Пример #29
0
 private void Awake()
 {
     this.GridLayoutGroup = this.GetComponent <GridLayoutGroup>();
     this.RectTransform   = this.GetComponent <RectTransform>();
     this.ToggleGroup     = this.gameObject.GetOrAddComponent <ToggleGroup>();
 }
Пример #30
0
        // Use this for initialization
        void Start()
        {
            //Get level data
            data = null;
            string    path      = JSON_PATH;
            TextAsset textAsset = Resources.Load <TextAsset>(path);

            data = textAsset.ToString().Split(';');

            //Get level solved data
            string[] levelSolvedData = PlayerPrefs.GetString(LevelManager.LEVELSOLVED_KEY).Split('_');
            int      highestLevelSolved;

            //Find the highest level that solved
            if (levelSolvedData.Length == 1)
            {
                highestLevelSolved = 0;
            }
            else
            {
                highestLevelSolved = int.Parse(levelSolvedData[0].Trim());
                for (int i = 1; i < levelSolvedData.Length; i++)
                {
                    if (highestLevelSolved < int.Parse(levelSolvedData[i]))
                    {
                        highestLevelSolved = int.Parse(levelSolvedData[i]);
                    }
                }
            }

            //Find all levels that solved in the pack
            float      range = highestLevelSolved / LEVELS_PER_PACK;
            List <int> listLevelSolvedInRange = new List <int>();

            if (highestLevelSolved != 0)
            {
                foreach (string o in levelSolvedData)
                {
                    if (range > 0)
                    {
                        if (int.Parse(o) >= range * LEVELS_PER_PACK && int.Parse(o) <= (range + 1) * LEVELS_PER_PACK)
                        {
                            listLevelSolvedInRange.Add(int.Parse(o));
                        }
                    }
                    else
                    {
                        listLevelSolvedInRange.Add(int.Parse(o));
                    }
                }
            }

            //Handle level detail scrollview
            #region Handle Level Detail Scrollview

            //Caculate level group
            float levelgroupNumber = Mathf.Ceil(data.Length / (float)buttonGroupPrefab.transform.childCount);
            ScrollToSelectedPack();
            int count = 0;

            //Generate level group, each level group has 6 levels
            for (int i = 1; i <= levelgroupNumber; i++)
            {
                GameObject buttonGroup = Instantiate(buttonGroupPrefab, levelDetailContent.transform.position, Quaternion.identity) as GameObject;
                buttonGroup.transform.SetParent(levelDetailContent.transform);
                buttonGroup.GetComponent <RectTransform>().localScale = new Vector3(1, 1, 1);

                int childCount = 0;
                for (int j = count; j < buttonGroup.transform.childCount * i; j++)
                {
                    if (j >= data.Length)
                    {
                        buttonGroup.transform.GetChild(childCount).gameObject.SetActive(false);
                    }
                    else
                    {
                        LevelData levelData = JsonUtility.FromJson <LevelData>(data[j]);
                        Transform theChild  = buttonGroup.transform.GetChild(childCount);
                        theChild.GetComponentInChildren <Text>().text = levelData.levelNumber.ToString();

                        LevelButtonController levelButtonController = theChild.GetComponent <LevelButtonController>();
                        GameObject            lockOb      = theChild.Find("Lock").gameObject;
                        GameObject            imgSolvedOb = theChild.Find("imgSolved").gameObject;
                        Image         levelImg            = theChild.Find("Mask").Find("Image").GetComponent <Image>();
                        RectTransform levelImgRT          = levelImg.GetComponent <RectTransform>();
                        string        file = Path.Combine(Application.persistentDataPath, levelData.levelNumber.ToString() + ".png");
                        //If this level is solved -> show the solved screenshot
                        if (LevelManager.IsLevelSolved(levelData.levelNumber) && File.Exists(file))
                        {
                            byte[]    bytes = File.ReadAllBytes(file);
                            Texture2D tex2D = new Texture2D(2, 2, TextureFormat.ARGB32, false);
                            tex2D.LoadImage(bytes);
                            float scaleFactor = levelImgRT.rect.height / tex2D.height;
                            levelImg.sprite = Sprite.Create(tex2D, new Rect(0, 0, tex2D.width, tex2D.height), Vector2.zero);
                            levelImg.SetNativeSize();
                            levelImg.transform.localScale = Vector3.one * scaleFactor;
                            imgSolvedOb.gameObject.SetActive(true);
                            lockOb.gameObject.SetActive(false);
                            maxUnlockedLevel = levelData.levelNumber;
                        }
                        else
                        {
                            Sprite sprite      = Resources.Load <Sprite>("Screenshots/" + levelData.levelNumber.ToString());
                            float  scaleFactor = levelImgRT.rect.height / sprite.rect.height;
                            levelImg.sprite = sprite;
                            levelImg.SetNativeSize();
                            levelImg.transform.localScale = Vector3.one * scaleFactor;
                            imgSolvedOb.gameObject.SetActive(false);

                            //Unlock all level from 0 to 6
                            if (levelData.levelNumber <= LEVELS_PER_PACK || levelData.levelNumber <= maxUnlockedLevel)
                            {
                                levelButtonController.isLocked = false;
                                lockOb.SetActive(false);
                                levelImg.color   = Color.white;
                                maxUnlockedLevel = levelData.levelNumber;
                            }
                            //Unlock all levels in range
                            else if (levelData.levelNumber <= (range + 1) * LEVELS_PER_PACK)
                            {
                                levelButtonController.isLocked = false;
                                lockOb.SetActive(false);
                                levelImg.color   = Color.white;
                                maxUnlockedLevel = levelData.levelNumber;
                            }
                            else //Check if reached complete percent -> unlock level
                            {
                                if (levelData.levelNumber <= (range + 2) * LEVELS_PER_PACK)
                                {
                                    float checkedPercent = Mathf.Ceil((packCompletePercentage * LEVELS_PER_PACK) / 100f);
                                    if (listLevelSolvedInRange.Count >= checkedPercent)
                                    {
                                        levelButtonController.isLocked = false;
                                        lockOb.SetActive(false);
                                        levelImg.color   = Color.white;
                                        maxUnlockedLevel = levelData.levelNumber;
                                    }
                                    else
                                    {
                                        levelButtonController.isLocked = true;
                                        levelImg.color = lockedColor;
                                    }
                                }
                                else
                                {
                                    levelButtonController.isLocked = true;
                                    levelImg.color = lockedColor;
                                }
                            }
                        }
                        count++;
                    }
                    childCount++;
                }
            }

            levelDetailScrollview.GetComponent <BetterScrollview>().DisableInvisibleItems();
            #endregion

            #region Handle Level Pack Scrollview

            //Caculate pack number
            float packNumber = Mathf.Ceil(data.Length / (float)LEVELS_PER_PACK);
            for (int i = 1; i <= packNumber; i++)
            {
                GameObject levelPackTemp = Instantiate(levelPackPrefab, levelPackContent.transform.position, Quaternion.identity) as GameObject;
                levelPackTemp.transform.SetParent(levelPackContent.transform);
                levelPackTemp.transform.localScale = new Vector3(1, 1, 1);
                LevelPackController levelPackControl = levelPackTemp.GetComponent <LevelPackController>();
                Transform           mainImgObj       = levelPackTemp.transform.Find("MainImg");
                Image         mainImg   = mainImgObj.Find("Mask").Find("Image").GetComponent <Image>();
                RectTransform mainImgRT = mainImg.GetComponent <RectTransform>();

                int startLevelPack;
                int endLevelPack;

                if (i == 1)
                {
                    startLevelPack = i;
                    endLevelPack   = LEVELS_PER_PACK;
                }
                else if (i == packNumber)
                {
                    startLevelPack = LEVELS_PER_PACK * (i - 1) + 1;
                    endLevelPack   = data.Length;
                }
                else
                {
                    startLevelPack = LEVELS_PER_PACK * (i - 1) + 1;
                    endLevelPack   = LEVELS_PER_PACK * i;
                }

                // Display level screenshot
                levelPackTemp.GetComponentInChildren <Text>().text = startLevelPack.ToString() + "-" + endLevelPack.ToString();
                string file = Path.Combine(Application.persistentDataPath, startLevelPack.ToString() + ".png");
                if (LevelManager.IsLevelSolved(startLevelPack) && File.Exists(file))
                {
                    byte[]    bytes = File.ReadAllBytes(file);
                    Texture2D tex2D = new Texture2D(2, 2, TextureFormat.ARGB32, false);
                    tex2D.LoadImage(bytes);
                    float scaleFactor = mainImgRT.rect.height / tex2D.height;
                    mainImg.sprite = Sprite.Create(tex2D, new Rect(0, 0, tex2D.width, tex2D.height), Vector2.zero);
                    mainImg.SetNativeSize();
                    mainImg.transform.localScale = Vector3.one * scaleFactor;
                }
                else
                {
                    Sprite sprite      = Resources.Load <Sprite>("Screenshots/" + startLevelPack.ToString());
                    float  scaleFactor = mainImgRT.rect.height / sprite.rect.height;
                    mainImg.sprite = sprite;
                    mainImg.SetNativeSize();
                    mainImg.transform.localScale = Vector3.one * scaleFactor;
                }

                // Set lock or unlock
                if (endLevelPack <= maxUnlockedLevel)
                {
                    levelPackTemp.transform.Find("Lock").gameObject.SetActive(false);
                    mainImg.color             = Color.white;
                    levelPackControl.isLocked = false;
                }
                else
                {
                    levelPackTemp.transform.Find("Lock").gameObject.SetActive(true);
                    mainImg.color             = lockedColor;
                    levelPackControl.isLocked = true;
                }

                GridLayoutGroup grlLevelPack            = levelPackContent.GetComponent <GridLayoutGroup>();
                float           xSizeOfLevelPackContent = (grlLevelPack.cellSize.x + grlLevelPack.spacing.x) * (packNumber - 1);
                RectTransform   levelPackContentRect    = levelPackContent.GetComponent <RectTransform>();
                levelPackContentRect.sizeDelta = new Vector2(xSizeOfLevelPackContent, levelPackContentRect.sizeDelta.y);
            }

            //levelPackScrollview.GetComponent<BetterScrollview>().DisableInvisibleItems();

            #endregion

            // Check if a new pack has been unlocked
            int oldMaxUnlockedLevel = PlayerPrefs.GetInt(MAX_UNLOCKED_LEVEL_PPK, LEVELS_PER_PACK);  // first pack's levels are unlocked from beginning

            if (maxUnlockedLevel > oldMaxUnlockedLevel)
            {
                PlayerPrefs.SetInt(MAX_UNLOCKED_LEVEL_PPK, maxUnlockedLevel);
            }

            //BetterScrollview packScroller = levelPackScrollview.GetComponent<BetterScrollview>();
            //packScroller.SnapToElement((GameManager.LevelLoaded - 1) / LEVELS_PER_PACK);
            //packScroller.DisableInvisibleItems();
        }