Forum begins after the advertisement:


Part 19 – Level Up Screen not showing

Home Forums Video Game Tutorial Series Creating a Rogue-like Shoot-em Up in Unity Part 19 – Level Up Screen not showing

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #15828
    Boby
    Participant
    Helpful?
    Up
    0
    ::

    Hello,

    When I levelup my player, I don’t have my levelup screen apear. Here is my codes :

    Player Datas :

    
    using System.Collections.Generic;
    using UnityEngine;
    using System;
    using UnityEngine.UI;
    using TMPro;
    
    namespace PLAYER{
        public class Player_Datas : MonoBehaviour
        {
            // V2
            //OBJECTIF : 
            // All the value used for the Player
    
            [Header("STATS")]
            Character_Data data; //Get the data for the player
            [Tooltip("Save the base stat of the player so we can return it if needed")]
            public Character_Data.Stats baseStats; //Assign the player's data as the base stat
            [Tooltip("The actual stat is the current stat running and modifying during the game")]
            [SerializeField] Character_Data.Stats actualStats;
    
            public Character_Data.Stats Stats {
                get {return actualStats; }
                set { actualStats = value; }
            }
    
            //Note : HP is hidding on the inspector
            float hp;
            public float currentHp{
                get {return hp;}
                //Apply the modification on the UI pannel
                set{
                    if(hp != value){
                        hp = value;
                        UpdateHP();
                    }
                }
            }
    
            [SerializeField] Collect_Item collector;
            public bool isMagnetize;
            public float magnetRadius;
    
            //Invicible-Frames
            [Header("Invicibles Frames")]
            public float invincibleDuration = 0.5f;
            public float invincibleTime;
            public bool isInvincible;
    
            [Header("UI")]
            public Image hpBar;
            public Image expBar;
            public TMP_Text levelText;
    
            [Space(5)]
    
            [Header("Damage Effect")]
            public ParticleSystem damageEffect;
    
            [Header("Armor Effect")]
            public ParticleSystem armorEffect; //If the player completly block an attack
    
            [Space(5)]
    
            [Header("INVENTORY SYSTEM")]
            Player_Inventory inventory;
            public int weapon_Index;
            public int passiveItem_Index;
    
            [Space(5)]
    
            //LEVEL / EXPERIENCES
            [Header("LEVELUP SYSTEM")]
            public int exp = 0;
            public int level = 1;
            public int expCap;
    
            [System.Serializable]
            public class LevelRange{
                public int startLevel;
                public int endLevel;
                public int expIncrease;
            }
    
            [Header("LevelUP Stats")]
            public List<LevelRange> lvlRanges;
    
            void Awake()
            {
                data = Character_Type_Selection.GetData();
                
                if(Character_Type_Selection.instance)
                    Character_Type_Selection.instance.DestroySingleton();
    
                inventory = GetComponentInChildren<Player_Inventory>();
                collector = GetComponentInChildren<Collect_Item>();
    
                baseStats = actualStats = data.stats;
                collector.SetRadius(actualStats.magnetForce);
                hp = actualStats.maxHP;
            }
    
            void Start(){
                //Spawn the starting weapon
                inventory.Add(data.startWeapon);
    
                //set the cap for the next level as the default expIncrease amount
                expCap = lvlRanges[0].expIncrease;
    
                GameManager.instance.AssignCharacterUI(data);
    
                UpdateHP();
                UpdateExp();
                UpdateLvl();
    
            }
    
            void Update(){
    
                //Set an Invicible frames to prevent continous dammage
                if(invincibleTime > 0)
                    invincibleTime -= Time.deltaTime;
                else if(isInvincible)
                    isInvincible = false;
    
                //Recovery
                Recover();
            }
    
            public void RecalulateStats(){
                actualStats = baseStats;
                foreach(Player_Inventory.Slot s in inventory.passive_Slots){
                    Passive p = s.item as Passive;
                    if(p)
                        actualStats += p.GetBoosts();
                }
                collector.SetRadius(actualStats.magnetForce);
            }
    
            public void Increase_EXP(int amount){
                exp += amount;
                LevelUp();
                UpdateExp();
            }
    
            void LevelUp(){
                //Check if we level up
                if(exp >= expCap){
                    level++; //ad 1 lvl
                    exp -= expCap; //restart the exp to 0
                    int expIncrease = 0;
                    foreach(LevelRange range in lvlRanges ){
                        if(level >= range.startLevel && level <= range.endLevel){
                            expIncrease = range.expIncrease;
                            break;
                        }
                    }
                    expCap += expIncrease;
    
                    UpdateLvl();
    
                    GameManager.instance.StartLevelUp();
    
                    //Verify if the next expCap is exceed after each levelup
                    if(exp >= expCap) LevelUp();
                }
            }
    
            void UpdateExp(){
                //Update the ui of the exp bar
                expBar.fillAmount = (float)exp / expCap;
            }
    
            void UpdateLvl(){
                levelText.text = "LVL" + level.ToString();
            }
    
            public void TakeDamage(float damage){
    
                if(!isInvincible){
    
                    //Take armor stat in acount before taking the damage
                    //Deacrease the damage amount by the armor protection value
                    damage -= actualStats.armor;
    
                    if(damage > 0){
                        //Deacrease the hp by the damage amount
                        currentHp -= damage;
    
                        //Play the damage effect if we have it
                        if(damageEffect) Destroy(Instantiate(damageEffect, transform.position, Quaternion.identity), 5f);
                        
                        //Kill the Player if the hp is 0
                        if(currentHp <= 0)
                            Kill();
                    }
                    //The damage is 0 = the armor completly block the damage
                    else
                         //Play the damage effect if we have it
                        if(armorEffect) Destroy(Instantiate(armorEffect, transform.position, Quaternion.identity), 5f);
                    
                    invincibleTime = invincibleDuration;
                    isInvincible = true;
                }
            }
    
            void UpdateHP(){
                hpBar.fillAmount = currentHp / actualStats.maxHP;
            }
    
            public void RecoverHP(float amount){
                //Only heal the player if we have less than the max hp
                if(currentHp < actualStats.maxHP){
                    currentHp += amount;
    
                    //Limit the maximum hp
                    if(currentHp > actualStats.maxHP)
                        currentHp = actualStats.maxHP;
                    
                    UpdateHP();
                }
            }
    
            public void Kill(){
                if(!GameManager.instance.isGameOver){
                    GameManager.instance.AssignLevelUP(level);
                    GameManager.instance.GameOver();
    
                    Debug.Log("Player dead");
                }
            }
    
            void Recover(){
                //Gradualy recover hp over time
                if(currentHp < actualStats.maxHP){
                    //Increase each seconds
                    currentHp += Stats.recovery * Time.deltaTime;
    
                    //Limit the maximum amount by the max hp we can have
                    if(currentHp > actualStats.maxHP)
                        currentHp = actualStats.maxHP;
                    
                    UpdateHP();
                }
            }
    
            public void Restore_HP(int amount){
                //if we have less than the max hp, we can restore hp
                if(currentHp < actualStats.maxHP){
                    currentHp += amount;
                    //Limit the maximum amount by the max hp we can have
                    if(currentHp > actualStats.maxHP)
                        currentHp = actualStats.maxHP;
                }
            }
    
        }
    }
    

    Player Inventory :

    
    using System;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using TMPro;
    
    namespace PLAYER{
        public class Player_Inventory : MonoBehaviour
        {
            [System.Serializable]
    
            //Manage the Slot
            public class Slot{
                public Item item;
                public Image image;
    
                //Assign a new item on the slot (Weapon or Passive Item)
                public void Assign(Item assignItem){
                    item = assignItem;
                    //Weapon Item
                    if(item is Weapon){
                        Weapon w = item as Weapon;
                        image.enabled = true;
                        image.sprite = w.data.icon;
                    }
                    //Passive item
                    else{
                        Passive w = item as Passive;
                        image.enabled = true;
                        image.sprite = w.data.icon;
                    }
                    Debug.Log($"Assigned : {item.name} to the player");
                }
    
                //Clear a slot where an item is assigned
                public void Clear(){
                    item = null;
                    image.enabled = false;
                    image.sprite = null;
                }
    
                //Verify if the slot is empty
                public bool isEmpty() {return item == null;}
            }
    
            public List<Slot> weapon_Slots = new List<Slot>(6);
            public List<Slot> passive_Slots = new List<Slot>(6);
    
            [Header("UI Elements")]
            //List of all the upgrades options for : weapons, passive items and ui
            public List<Weapon_Data> available_Weapons = new List<Weapon_Data>();
            public List<Passive_Data> available_Passives = new List<Passive_Data>();
            public UI_UpgradeWindow upgradeWindow;
    
            Player_Datas player;
    
            void Awake(){
                player = GetComponent<Player_Datas>();
            }
    
            //Verify if the item has an item of a certain type
            public bool Has(Item_Data type) { return Get(type); }
    
            //ITEM TYPE
            public Item Get(Item_Data type){
                //Weapon type
                if(type is Weapon_Data) return Get(type as Weapon_Data);
                //Passive type
                if(type is Passive_Data) return Get(type as Passive_Data);
                //No type
                return null;
            }
    
            //FIND PASSIVE TYPE
            public Passive Get(Passive_Data type){
                foreach(Slot s in passive_Slots){
                    Passive p = s.item as Passive;
                    if(p.data && p.data == type) return p;
                }
                return null;
            }
    
            //FIND WEAPON TYPR
            public Weapon Get(Weapon_Data type){
                foreach(Slot s in weapon_Slots){
                    Weapon w = s.item as Weapon;
                    if(w.data && w.data == type) return w;
                }
                return null;
            }
    
            //Remove a Weapon of particular type
            public bool Remove(Weapon_Data data, bool canRemoveUpgrade = false){
                //Remove this weapon from the upgrading pool
                if(canRemoveUpgrade) available_Weapons.Remove(data);
    
                for(int i = 0; i < weapon_Slots.Count; i++){
                    Weapon w = weapon_Slots[i].item as Weapon;
                    if(w.data == data){
                        weapon_Slots[i].Clear();
                        w.UnEquip();
                        Destroy(w.gameObject);
                        return true;
                    }
                }
                return false;
            }
    
            //Remove a Passive Item of particular type
            public bool Remove(Passive_Data data, bool canRemoveUpgrade = false){
                //Remove this weapon from the upgrading pool
                if(canRemoveUpgrade) available_Passives.Remove(data);
    
                for(int i = 0; i < available_Passives.Count; i++){
                    Passive p = passive_Slots[i].item as Passive;
                    if(p.data == data){
                        passive_Slots[i].Clear();
                        p.UnEquip();
                        Destroy(p.gameObject);
                        return true;
                    }
                }
                return false;
            }
    
            public bool Remove(Item_Data data, bool canRemoveUpgrade = false){
                if(data is Passive_Data) return Remove(data as Passive_Data, canRemoveUpgrade);
                else if(data is Weapon_Data) return Remove(data as Weapon_Data, canRemoveUpgrade);
                return false;
            }
    
            //Find an empty slot, add the weapon of the certain type and return the slot index
            public int Add(Weapon_Data data){
    
                int slotNum = -1; //= = the first so -1 is outside
    
                //Search an empty slot
                for(int i = 0; i < weapon_Slots.Capacity; i++){
                    if(weapon_Slots[i].isEmpty()){
                        slotNum = i;
                        break;
                    }
                }
    
                //No Empty Slot exist
                if(slotNum < 0) return slotNum;
    
                //Create the weapon in the slot
                Type weaponType = Type.GetType(data.behaviour);
    
                if(weaponType != null){
                    //Spawn the Weapon on the scene
                    GameObject go = new GameObject(data.baseStats.name + "Weapon Controller");
                    Weapon weaponSpawn = (Weapon)go.AddComponent(weaponType);
                    weaponSpawn.transform.SetParent(transform);
                    weaponSpawn.transform.localPosition = Vector2.zero;
                    weaponSpawn.Initialize(data);
                    weaponSpawn.OnEquip();
    
                    //Assign it on the slot
                    weapon_Slots[slotNum].Assign(weaponSpawn);
    
                    //Close the LevelUP UI
                    if(GameManager.instance != null && GameManager.instance.isLevelUP)
                        GameManager.instance.EndLevelUp();
    
                    return slotNum;
                }
                else
                    Debug.LogWarning($"Invalid Weapon type for {data.name}");
    
                return -1;
            }
    
            //Find an empty slot, add the passive item of the certain type and return the slot index
            public int Add(Passive_Data data){
    
                int slotNum = -1; //= = the first so -1 is outside
    
                //Search an empty slot
                for(int i = 0; i < passive_Slots.Capacity; i++){
                    if(passive_Slots[i].isEmpty()){
                        slotNum = i;
                        break;
                    }
                }
    
                //No Empty Slot exist
                if(slotNum < 0) return slotNum;
    
                //Spawn the Weapon on the scene
                GameObject go = new GameObject(data.baseStats.name + "Passive Controller");
                Passive p = go.AddComponent<Passive>();
                p.Initialize(data);
                p.transform.SetParent(transform);
                p.transform.localPosition = Vector2.zero;
    
                //Assign it on the slot
                passive_Slots[slotNum].Assign(p);
    
                //Close the LevelUP UI
                if(GameManager.instance != null && GameManager.instance.isLevelUP)
                    GameManager.instance.EndLevelUp();
    
                player.RecalulateStats();
    
                return slotNum;
            }
    
            //Determine the type if we don't know
            public int Add(Item_Data data){
                if(data is Weapon_Data) return Add(data as Weapon_Data);
                else if(data is Passive_Data) return Add(data as Passive_Data);
                return -1;
            }
    
            //Check for empty slot (if empty, we can add one item)
            int GetSlotsLeft(List<Slot> slots){
                int count = 0;
                foreach(Slot s in slots){ if(s.isEmpty()) count++; }
                return count;
            }
    
            //Levelup an item
            public bool LevelUP(Item item){
                if(!item.DoLevelUp()){
                    Debug.LogWarning($"Failed to levelup {item.name}");
                    return false;
                }
                if(GameManager.instance != null && GameManager.instance.isLevelUP){
                    GameManager.instance.EndLevelUp();
                }
                if(item is Passive) player.RecalulateStats();
                return true;
            }
            public bool LevelUP(Item_Data data){
                Item item = Get(data);
                if(item) return LevelUP(item);
                return false;
            }
    
            //Determine the upgrade options to appear
            void ApplyUpgradeOptions(){
                //Available Upgrades in an empty list used for filtering
                List<Item_Data> available_Upgrades = new List<Item_Data>();
                //All the Upgrades
                List<Item_Data> all_Upgrades = new List<Item_Data>(available_Upgrades);
                all_Upgrades.AddRange(available_Upgrades);
    
                //Set how many slot upgrades left (default 6)
                int weapon_Slots_Left = GetSlotsLeft(weapon_Slots);
                int passive_Slots_Left = GetSlotsLeft(passive_Slots);
    
                //Loop inside the availables weapons and passive and find the possible updates
                foreach(Item_Data data in all_Upgrades){
    
                    // 1 - Check if we already have a weapon/passive and if it is, check if our level is not the maximum
                    Item obj = Get(data);
                    if(obj)
                        if(obj.level < data.maxLevel) available_Upgrades.Add(data);
                    // 2 - We don't found this weapon/passive in our slot so check if we have enough space to add it
                    else{
                        if(data is Weapon_Data && weapon_Slots_Left > 0) available_Upgrades.Add(data);
                        else if(data is Passive_Data && passive_Slots_Left > 0) available_Upgrades.Add(data);
                    }
                }
    
                //Display the UI Windows Uograde
                int dispo_Upgrades_Count = available_Upgrades.Count;
                if(dispo_Upgrades_Count > 0){
                    Debug.Log("dispo upgrades");
                    bool getExtraItem = 1f - 1f / player.Stats.luck > UnityEngine.Random.value;
                    if(getExtraItem || dispo_Upgrades_Count < upgradeWindow.maxOptions) upgradeWindow.SetUpgrades(this, available_Upgrades, upgradeWindow.maxOptions);
                    else upgradeWindow.SetUpgrades(this, available_Upgrades, (upgradeWindow.maxOptions - 1), $"Increase your LUCK to get {upgradeWindow.maxOptions} Items !");
                }
                else if(GameManager.instance != null && GameManager.instance.isLevelUP)
                    GameManager.instance.EndLevelUp();
            }
    
            public void RemoveAndApplyUpgrades(){
                ApplyUpgradeOptions();
            }
        }
    }
    

    Game Manager :

    
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using UnityEngine.InputSystem;
    using TMPro;
    using PLAYER;
    
    public class GameManager : MonoBehaviour
    {
        public static GameManager instance;
    
        //Define the state of the game
        public enum Game_State : byte{
            Gameplay,
            Paused,
            GameOver,
            LevelUp
        }
    
        //Store the current state of the game
        [Tooltip("Track and apply the current state of the game")]
        public Game_State state;
        //Store the previous state
        [Tooltip("Track the previous state of the game so we can go back if we change the state")]
        public Game_State state_Previous;
    
        [Header("Damage Text Settings")]
        [Tooltip("Set a special canvas to show the damage effect on it")]
        public Canvas damageTextCanvas;
        [Tooltip("Set the font size of the damage text")]
        public float textTypoSize = 20;
        [Tooltip("Add a special font asset for the damage effect")]
        public TMP_FontAsset textTypo;
        [Tooltip("Set the camera of the game so we can track correctly the enemy and show the canvas")]
        public Camera mainCamera;
    
        [Header("Screens")]
        public GameObject pause_Screen, highsore_Screen, levelUp_Screen;
        int stackedLevels = 0;
    
        [Header("Display Stats")]
        //Pannel where all the stats are showing, the player can see them
        public TMP_Text hp_Display;
        public TMP_Text recovery_Display;
        public TMP_Text moveSpeed_Display;
        public TMP_Text might_Display;
        public TMP_Text projectileSpeed_Display;
        public TMP_Text magnetForce_Display;
    
        [Header("Results Display")]
        //A pannel resuming the final stats of the player after he died
        public Image characterImage;
        public TMP_Text characterName;
        public TMP_Text levelReached;
        public TMP_Text timeSurviveDisplay;
    
        [Header("StopWatched")]
        [Tooltip("Limit the maxium time limit of all the game.")]
        public float timeLimit; //Limite of the time in seconds
        float stopTime; //Current time elapsed since the time started
        [Tooltip("Set the timer to display")]
        public TMP_Text timerDisplay;
    
        //Get the player
        public GameObject playerObj;
    
        [Tooltip("If the game state is Game Over, return the Pause Screen")]
        public bool isGameOver {get {return state == Game_State.Paused; }}
    
        [Tooltip("If the game state is Level UP, return the LevelUP Screen")]
        public bool isLevelUP {get {return state == Game_State.LevelUp; }}
    
        public float GetElapsedTime(){return stopTime; }
    
        void Awake(){
            //Set only one instance of game manager or destroy the extras
            if(instance == null)
                instance = this;
            else
                Destroy(gameObject);
    
            DisableScreens();
        }
    
        void Update(){
            //Define the logic for each states
            switch(state){
                case Game_State.Gameplay:
                    CheckForPauseAndResume();
                    UpdateStopWatch();
                    break;
                case Game_State.Paused:
                    CheckForPauseAndResume();
                    break;
                case Game_State.GameOver:
                case Game_State.LevelUp:
                    break;
                default:
                    Debug.Log("State not defined");
                    break;
            }
        }
    
        public void ChangeState(Game_State newState){
            state_Previous = state; //Save the previous state to back easly
            state = newState; //Set the new state as the current state
        }
    
        public void PauseGame(){
            if(state != Game_State.Paused){
                ChangeState(Game_State.Paused);
                Time.timeScale = 0; //Stop the complete game time
                pause_Screen.SetActive(true);
            }
        }
    
        public void ResumeGame(){
            if(state == Game_State.Paused){
                ChangeState(state_Previous);
                Time.timeScale = 1; //Reset the complete game
                pause_Screen.SetActive(false);
            }
        }
    
        void CheckForPauseAndResume(){
            if(Input.GetKeyDown(KeyCode.Escape)){
                if(state == Game_State.Paused)
                    ResumeGame();
                else
                    PauseGame();
            }
        }
    
        void DisableScreens(){
            pause_Screen.SetActive(false);
            highsore_Screen.SetActive(false);
            levelUp_Screen.SetActive(false);
        }
    
        public void GameOver(){
            timeSurviveDisplay.text = timerDisplay.text;
            ChangeState(Game_State.GameOver);
            Time.timeScale = 0f;
            DisplayResults();
        }
    
        void DisplayResults(){
            highsore_Screen.SetActive(true);
        }
    
        public void AssignCharacterUI(Character_Data characterData){
            characterImage.sprite = characterData.icon;
            characterName.text = characterData.name;
        }
    
        public void StartLevelUp(){
            ChangeState(Game_State.LevelUp);
            if(levelUp_Screen.activeSelf) stackedLevels++;
            else{
                Time.timeScale = 0f;
                levelUp_Screen.SetActive(true);
                playerObj.SendMessage("RemoveAndApplyUpgrades");
            }
            
        }
    
        public void EndLevelUp(){
            Time.timeScale = 1f;
            levelUp_Screen.SetActive(false);
            ChangeState(Game_State.Gameplay);
    
            if(stackedLevels > 0){
                stackedLevels--;
                StartLevelUp();
            }
        }
    
        public void AssignLevelUP(int levelData){
            levelReached.text = levelData.ToString();
        }
    
        public void UpdateStopWatch(){
            stopTime += Time.deltaTime;
            UpdateStopWatchDisplay();
    
            if(stopTime >= timeLimit){
                playerObj.SendMessage("Kill");
            }
                
        }
    
        void UpdateStopWatchDisplay(){
            int minutes = Mathf.FloorToInt(stopTime/60);
            int seconds = Mathf.FloorToInt(stopTime % 60);
    
            timerDisplay.text = string.Format("{0:00}:{1:00}", minutes, seconds);
        }
    
        //note for me : not working too
        IEnumerator GenerateFloatingText(string text, Transform target, float duration = 1f, float speed = 50f){
            //Start generating the floating text
            GameObject textObj = new GameObject("Damage Floating");
            RectTransform rect = textObj.AddComponent<RectTransform>();
            TextMeshProUGUI tmpro = textObj.AddComponent<TextMeshProUGUI>();
            tmpro.text = text;
            tmpro.horizontalAlignment = HorizontalAlignmentOptions.Center;
            tmpro.verticalAlignment = VerticalAlignmentOptions.Middle;
            tmpro.fontSize = textTypoSize;
            if(textTypo) tmpro.font = textTypo;
            rect.position = mainCamera.WorldToScreenPoint(target.position);
    
            //Destroy after the duration time
            Destroy(textObj, duration);
    
            //Parent to the canvas
            textObj.transform.SetParent(instance.damageTextCanvas.transform);
            textObj.transform.SetSiblingIndex(0);
    
            //Move and fade out the text
            WaitForEndOfFrame w = new WaitForEndOfFrame();
            float t = 0;
            float yOffset = 0;
            Vector3 lastPos = target.position;
            while(t < duration){
                
                //Break the loop if we don't have the rect transform
                if(!rect) break;
    
                //Fade out the text
                tmpro.color = new Color(tmpro.color.r, tmpro.color.g, tmpro.color.b, 1- t / duration);
    
                if(target) lastPos = target.position;
    
                //Move the text
                yOffset += speed * Time.deltaTime;
                rect.position = mainCamera.WorldToScreenPoint(lastPos + new Vector3(0, yOffset));
    
                //Wait a frame and update
                yield return w;
                t += Time.deltaTime;
            }
        }
    
        public static void FloatingText(string text, Transform target, float duration = 1f, float speed = 50f){
    
            //Prevent any error to oblige the canvas to be set, if not, do nothing
            if(!instance.damageTextCanvas) return;
    
            //If we have a canvas but the camera is not correctly set, set the main camera by default
            if(!instance.mainCamera) instance.mainCamera = Camera.main;
    
            //Start the effect
            instance.StartCoroutine(instance.GenerateFloatingText(text, target, duration, speed));
        }
    }
    

    UI Upgrade Windows :

    
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using PLAYER;
    using TMPro;
    
    [RequireComponent(typeof(VerticalLayoutGroup))]
    public class UI_UpgradeWindow : MonoBehaviour
    {
        //Access to the padding / spacing on the layout
        VerticalLayoutGroup verticalLayout;
    
        //Main Upgrade pannel template
        public RectTransform upgrade_Option_Template;
        public TextMeshProUGUI tooltip_Template;
    
        [Header("Settings")]
        //Set the maximum number of options to display on screen
        public int maxOptions = 4;
        //The text to show when a new upgrade is availible
        public string newText = "New";
        //Color of the new text
        public Color newText_Color = Color.red;
        //Color of the level text
        public Color levelText_Color = Color.black;
    
        [Header("Paths Elements")]
        //Set all the name inside the inspector
        public string iconPath = "Icon Holder/Icon", namePath = "Info Holder/Name", descriptionPath = "Info Holder/Description", buttonPath = "Button", levelPath = "Icon Holder/Level";
    
        //Private variables to track the comportement
        //Rect Transform of the element
        RectTransform rectTransform; 
        //Default heign of the upgdrade ui
        float option_Height;
        //Track the number of options currently active on the pannel (new, level, etc)
        int activeOptions;
        //List of all the upgrades options (buttons)
        List<RectTransform> upgradeOptions = new List<RectTransform>();
        //Track the screen size each frame to be able to modify the size
        Vector2 lastScreen;
    
        public void SetUpgrades(Player_Inventory inventory, List<Item_Data> possible_Upgrades, int pick = 3, string tooltip = ""){
    
            //Define the number to show on screen
            pick = Mathf.Min(maxOptions, pick);
    
            //Create an upgrade if we don't have enough (the max options set is more than the real number of options )
            if(maxOptions > upgradeOptions.Count){
                for(int i = upgradeOptions.Count; i < pick; i++){
                    GameObject go = Instantiate(upgrade_Option_Template.gameObject, transform);
                    upgradeOptions.Add((RectTransform)go.transform);
                }
            }
    
            //Tooltip is provided, active the tooltip
            tooltip_Template.text = tooltip;
            tooltip_Template.gameObject.SetActive(tooltip.Trim() != ""); //Verify if it's not empty
    
            //Activate only the number of upgrades options we need.
            activeOptions = 0;
            int totalOptions = possible_Upgrades.Count;
            foreach(RectTransform r in upgradeOptions){
                if(activeOptions < pick && activeOptions < totalOptions){
                    //Show the upgrade
                    r.gameObject.SetActive(true);
    
                    //Select randomly one upgrade possible and remove it from the list of availables (prevent duplicatas)
                    Item_Data upgrade_Selected = possible_Upgrades[Random.Range(0, possible_Upgrades.Count)];
                    possible_Upgrades.Remove(upgrade_Selected);
                    Item item = inventory.Get(upgrade_Selected);
    
                    // ----------------------------- NAME ------------------------------------ //
                    //Select the name text in the UI
                    TextMeshProUGUI name = r.Find(namePath).GetComponent<TextMeshProUGUI>();
                    //Apply the name of the selected upgrade on the UI
                    if(name) name.text = upgrade_Selected.name;
                    // ------------------------------------------------------------------------ //
    
                    
                    // ----------------------------- LEVEL ------------------------------------ //
                    //Add the level or the "New" text if it's a new item
                    //Select the name text in the UI
                    TextMeshProUGUI level = r.Find(levelPath).GetComponent<TextMeshProUGUI>();
                    //Level found
                    if(level){
    
                        //The Player has this item so we update the level to match
                        if(item){
                            //The item is on his max level
                            if(item.level >= item.maxLevel){
                                level.text = "Maximum !";
                                level.color = newText_Color;
                            }
                            //Update the level (adding +1 lvl provide the next level of the item)
                            else{
                                level.text = upgrade_Selected.GetLevelData(item.level + 1).name;
                                level.color = levelText_Color;
                            }
                        }
                        //The Player don't have this item, add the NEW text
                        else{
                            level.text = newText;
                            level.color = newText_Color;
                        }
                    }//level
                    // ----------------------------------------------------------------------- //
    
                    // --------------------------- DESCRIPTION ------------------------------- //
                    //Select the description text in the UI
                    TextMeshProUGUI description = r.Find(descriptionPath).GetComponent<TextMeshProUGUI>();
                   
                    //Description found
                    if(description){
                        //The Player has this item so we levelup it to promote the next level of this item
                        if(item)
                            description.text = upgrade_Selected.GetLevelData(item.level + 1).description;
                        //The Player don't have this item so we display the level 1
                        else
                            description.text = upgrade_Selected.GetLevelData(1).description;
                    }
                    // ----------------------------------------------------------------------- //
    
                    // ------------------------------  ICON  --------------------------------- //
                    //Select the icon image in the UI
                    Image icon = r.Find(iconPath).GetComponent<Image>();
    
                    //Icon founnd
                    if(icon) icon.sprite = upgrade_Selected.icon;
                    // ----------------------------------------------------------------------- //
    
                    //Get the button 
                    Button btn = r.Find(buttonPath).GetComponent<Button>();
                    //Button found
                    if(btn){
                        //Clear
                        btn.onClick.RemoveAllListeners();
                        //Player has this item so levelup the current item on the inventory
                        if(item)
                            btn.onClick.AddListener(() => inventory.LevelUP(item));
                        //Player don't have this item, add it to the inventory
                        else
                            btn.onClick.AddListener(() => inventory.Add(upgrade_Selected));
                    }
    
                    activeOptions++;
                }//if activeOptions
                //Don't find any options, disable the pannel
                else r.gameObject.SetActive(false);
            }//foreach loop
    
            //Sizes all the elemtnto fit correctly
            RecalulateLayout();
        }
    
        //Called when the size of the windows change.
        void RecalulateLayout(){
            // Calculate the total available height for all options, 
            // then divides it by the number of options to perfectly fit 
            // all the upgrades inside the layout.
            option_Height = (rectTransform.rect.height - verticalLayout.padding.top - verticalLayout.padding.bottom - (maxOptions - 1) * verticalLayout.spacing);
            
            // Maximum options display
            if(activeOptions == maxOptions && tooltip_Template.gameObject.activeSelf)
                option_Height /= maxOptions + 1;
            //Les than maximum
            else
                option_Height /= maxOptions;
            
            //Recalculates the height of the tooltip if it's currently active
            if(tooltip_Template.gameObject.activeSelf){
                RectTransform tooltipRect = (RectTransform)tooltip_Template.transform;
                tooltip_Template.gameObject.SetActive(true);
                tooltipRect.sizeDelta = new Vector2(tooltipRect.sizeDelta.x, option_Height);
                tooltip_Template.transform.SetAsLastSibling();
            }
    
            //Set the height of every active Upgrades Option
            foreach(RectTransform r in upgradeOptions){
                if(!r.gameObject.activeSelf) continue;
                r.sizeDelta = new Vector2(r.sizeDelta.x, option_Height);
            }
        }
    
        //Track and apply modifications every frames
        void Update(){
            if(lastScreen.x != Screen.width || lastScreen.y != Screen.height){
                RecalulateLayout();
                lastScreen = new Vector2(Screen.width, Screen.height);
            }
        }
    
        void Awake(){
            verticalLayout = GetComponentInChildren<VerticalLayoutGroup>();
            if(tooltip_Template) tooltip_Template.gameObject.SetActive(false);
            if(upgrade_Option_Template) upgradeOptions.Add(upgrade_Option_Template);
            rectTransform = (RectTransform)transform;
        }
    
        void Reset(){
            //Automaticaly find a game object named "Upgrade Options" and set it as the upgrade_Option_Template
            upgrade_Option_Template = (RectTransform)transform.Find("Upgrade Option");
    
            //Automaticaly find a game object named "Tooltip" and set it as the tooltip_Template
            tooltip_Template = transform.Find("Tooltip").GetComponentInChildren<TextMeshProUGUI>();
        }
    }
    

    My SetUpgrades is not calling from my ApplyUpgradeOptions that is not calling from my RemoveAndApplyUpgrades that is not calling from the Game Manager but the levelUp of my player data is calling and my LevelUp from my Game Manager as well.

    Thank you for your help

    #15881
    Terence
    Keymaster
    Helpful?
    Up
    0
    ::

    Sorry for missing your message Boby. You posted it in the wrong forum and I missed it.

    Can you add the following into the GameManager? Then let me know if the “Level up screen activated” message prints when you level up.

        public void StartLevelUp(){
            ChangeState(Game_State.LevelUp);
            if(levelUp_Screen.activeSelf) stackedLevels++;
            else{
                Time.timeScale = 0f;
                print("Level up screen activated");
                levelUp_Screen.SetActive(true);
                playerObj.SendMessage("RemoveAndApplyUpgrades");
            }
            
        }
Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: