Forum begins after the advertisement:
[Part 15] Spawn multi-weapon when clicking the button
Home › Forums › Video Game Tutorial Series › Creating a Rogue-like Shoot-em Up in Unity › [Part 15] Spawn multi-weapon when clicking the button
- This topic has 11 replies, 2 voices, and was last updated 6 months, 2 weeks ago by
Ngọc Đức Hoàng.
-
AuthorPosts
-
February 23, 2024 at 10:43 am #13391
Ngọc Đức Hoàng
Participant::After the livestream #4, if the initial weapon is Knife, then after clicking on the button to receive the second weapon, the second number of weapons on Inventory is 5 (EX: Garlic will appear 5 controllers and 5 image. ). Everyone can help me thank you. It is code of PlayerInventory :
public class PlayerInventory : MonoBehaviour { public struct Slot { public Weapon weapon; public Image UI; } // public List<Slot> weaponSlots = new List<Slot>(6); public List<Weapon> weaponSlots = new List<Weapon>(6); public List<Image> weaponsUISlot = new List<Image>(6); public List<PassiveItem> passiveItemSlots = new List<PassiveItem>(6); public int[] passiveItemLevels = new int[6]; public List<Image> passiveItemUISlots = new List<Image>(6); [System.Serializable] public class WeaponUpgrade { public int weaponUpgradeIndex; // luu tru chi muc cua vk nang cap public GameObject initialWeapon; public WeaponData weaponData; } [System.Serializable] public class PassiveItemUpgrade { public int passiveItemUpgradeIndex; public GameObject initialPassiveItem; public PassiveItemScriptableObject passiveItemData; } [System.Serializable] public class UpgardeUI { public TextMeshProUGUI upgradeNameDisplay; public TextMeshProUGUI upgradeDescriptionDisplay; public Image upgradeIcon; public Button upgradeButton; } [Header("UI Elements")] public List<WeaponData> availableWeapons = new List<WeaponData>();// list of upgrade options for weapon public List<PassiveItemUpgrade> passiveItemUpgradeOptions = new List<PassiveItemUpgrade>(); public List<UpgardeUI> upgradeUIOptions = new List<UpgardeUI>(); public List<WeaponEvolutionBlueprint> weaponEvolutions = new List<WeaponEvolutionBlueprint>(); PlayerStats player; private void Start() { player = GetComponent<PlayerStats>(); } public void AddWeapon(int slotIndex, Weapon weapon) { weapon.OnEquip(); weaponSlots[slotIndex] = weapon; weaponsUISlot[slotIndex].enabled = true; // chi bat khi vk dc them weaponsUISlot[slotIndex].sprite = weapon.data.icon; if (GameManager.instance != null && GameManager.instance.choosingUpgrade) // sau khi chon nang cap thi game se tiep tuc { GameManager.instance.EndLevelUp(); } } public void AddPassiveItem(int slotIndex, PassiveItem passiveItem) { passiveItemSlots[slotIndex] = passiveItem; passiveItemLevels[slotIndex] = passiveItem.passiveItemData.Level; // passiveItemUISlots[slotIndex].enabled = true;// chi bat khi vp dc them // passiveItemUISlots[slotIndex].sprite = passiveItem.passiveItemData.Icon; if (GameManager.instance != null && GameManager.instance.choosingUpgrade) { GameManager.instance.EndLevelUp(); } } public void LevelUpWeapon(int slotIndex, int upgradeIndex) { if (weaponSlots.Count > slotIndex) { Weapon weapon = weaponSlots[slotIndex]; if (!weapon.DoLevelUp()) { Debug.LogWarning(string.Format("Fail to level up {0}.", weapon.name)); return; } // weapon.DoLevelUp(); } if (GameManager.instance != null && GameManager.instance.choosingUpgrade) { GameManager.instance.EndLevelUp(); } } public void LevelUpPassiveItem(int slotIndex, int upgradeIndex) { if (passiveItemSlots.Count > slotIndex) { PassiveItem passiveItem = passiveItemSlots[slotIndex]; if (!passiveItem.passiveItemData.NextLevelPrefab) { Debug.LogError("No next levell for" + passiveItem.name); return; } GameObject upgradedPassiveItem = Instantiate(passiveItem.passiveItemData.NextLevelPrefab, transform.position, Quaternion.identity); upgradedPassiveItem.transform.SetParent(transform); AddPassiveItem(slotIndex, upgradedPassiveItem.GetComponent<PassiveItem>()); Destroy(passiveItem.gameObject); passiveItemLevels[slotIndex] = upgradedPassiveItem.GetComponent<PassiveItem>().passiveItemData.Level; passiveItemUpgradeOptions[upgradeIndex].passiveItemData = upgradedPassiveItem.GetComponent<PassiveItem>().passiveItemData; if (GameManager.instance != null && GameManager.instance.choosingUpgrade) { GameManager.instance.EndLevelUp(); } } } // Xac dinh loai nang cap nao ne xuaat hien void ApplyUpgradeOptions() { // Make a duplicate of the availble weapon/ passive ungrade lists // so we can iterate through them in the function List<WeaponData> availbleWeaponUpgrades = new List<WeaponData>(availableWeapons); List<PassiveItemUpgrade> availblePassiveItemUpgrades = new List<PassiveItemUpgrade>(passiveItemUpgradeOptions); // //Iterate through each slot in the upgrade UI foreach (UpgardeUI upgradeOption in upgradeUIOptions) { // if there are no more availble upgrade, then we abort if (availbleWeaponUpgrades.Count == 0 && availblePassiveItemUpgrades.Count == 0) // neu chua co vk hoac vat pham nao dc chon { return; } // determine wheter this upgrade shoulb be for passive or active weapons. int upgradeType; if (availbleWeaponUpgrades.Count == 0) { upgradeType = 2; } else if (availblePassiveItemUpgrades.Count == 0) { upgradeType = 1; } else { upgradeType = Random.Range(1, 3); } // Generates an active weapon upgrade if (upgradeType == 1) { // chon 1 vu khi va xoa no di de trong hang cho ko co 2 vk giong nhau WeaponData chosenWeaponUpgrade = availbleWeaponUpgrades[Random.Range(0, availbleWeaponUpgrades.Count)]; availbleWeaponUpgrades.Remove(chosenWeaponUpgrade);// xoa di cac vk da dc chon de ds chi gom cac vk khac nhau // Ensure that the selected weapon data is valid if (chosenWeaponUpgrade != null) { EnableUpgradeUI(upgradeOption); // goi khi vk dc dua len UI //Loop through all our existing weapons. if we find a match, we will hook an event listener to the button // that will level up the weapon when this upgrade option is clicked. bool isLevelUp = false; for (int i = 0; i < weaponSlots.Count; i++) { if (weaponSlots[i] != null && weaponSlots[i].data == chosenWeaponUpgrade) // ktra vu khi da ton tai hay chua { if (chosenWeaponUpgrade.maxLevel <= weaponSlots[i].currentLevel + 1) // ktra khi vk toi muc toi da se ko con nan cap nua { DisableUpgradeUI(upgradeOption); // neu vk dat max ko can dua vao UI nua break; } upgradeOption.upgradeButton.onClick.AddListener(() => LevelUpWeapon(i, i)); print(chosenWeaponUpgrade.name + "is a old weapon"); // set des and name to be that of the next level Weapon.Stats nextLevel = chosenWeaponUpgrade.GetLevelData(weaponSlots[i].currentLevel + 1); upgradeOption.upgradeDescriptionDisplay.text = nextLevel.description; upgradeOption.upgradeNameDisplay.text = nextLevel.name; upgradeOption.upgradeIcon.sprite = chosenWeaponUpgrade.icon; isLevelUp = true; break; } // if the code gets here, it means that we will be adding a new weapon , instead of upgrading an existing weapon. if (!isLevelUp) { print(chosenWeaponUpgrade.name + "is a new weapon"); upgradeOption.upgradeButton.onClick.AddListener(() => player.SpawnWeapon(chosenWeaponUpgrade)); // apply button function upgradeOption.upgradeDescriptionDisplay.text = chosenWeaponUpgrade.baseStats.description; upgradeOption.upgradeNameDisplay.text = chosenWeaponUpgrade.baseStats.name; upgradeOption.upgradeIcon.sprite = chosenWeaponUpgrade.icon; } } } } else if (upgradeType == 2) { PassiveItemUpgrade chosenPassiveItemUpgrade = availblePassiveItemUpgrades[Random.Range(0, availblePassiveItemUpgrades.Count)]; availblePassiveItemUpgrades.Remove(chosenPassiveItemUpgrade); if (chosenPassiveItemUpgrade != null) { EnableUpgradeUI(upgradeOption); bool newPassiveItem = false; for (int i = 0; i < passiveItemSlots.Count; i++) { if (passiveItemSlots[i] != null && passiveItemSlots[i].passiveItemData == chosenPassiveItemUpgrade.passiveItemData) // ktra vu khi da ton tai hay chua { newPassiveItem = false; if (!newPassiveItem) { if (!chosenPassiveItemUpgrade.passiveItemData.NextLevelPrefab) // ktra khi vp toi muc toi da se ko con nan cap nua { break; } upgradeOption.upgradeButton.onClick.AddListener(() => LevelUpPassiveItem(i, chosenPassiveItemUpgrade.passiveItemUpgradeIndex)); upgradeOption.upgradeDescriptionDisplay.text = chosenPassiveItemUpgrade.passiveItemData.NextLevelPrefab.GetComponent<PassiveItem>().passiveItemData.Description; upgradeOption.upgradeNameDisplay.text = chosenPassiveItemUpgrade.passiveItemData.NextLevelPrefab.GetComponent<PassiveItem>().passiveItemData.Name; } break; } else { newPassiveItem = true; } } if (newPassiveItem) { upgradeOption.upgradeButton.onClick.AddListener(() => player.SpawnPassiveItem(chosenPassiveItemUpgrade.initialPassiveItem)); upgradeOption.upgradeDescriptionDisplay.text = chosenPassiveItemUpgrade.passiveItemData.Description; upgradeOption.upgradeNameDisplay.text = chosenPassiveItemUpgrade.passiveItemData.Name; } upgradeOption.upgradeIcon.sprite = chosenPassiveItemUpgrade.passiveItemData.Icon; } } } } void RemoveUpgradeoptions() { foreach (UpgardeUI upgradeOption in upgradeUIOptions) { upgradeOption.upgradeButton.onClick.RemoveAllListeners(); DisableUpgradeUI(upgradeOption); // disable all UI option before applying upgrades to them } } public void RemoveAndApplyUpgrades() // co the su dung sendmessage de goi ham nay 1 cach gian tiep maf ko can truc tiep truy cap { RemoveUpgradeoptions(); ApplyUpgradeOptions(); } void DisableUpgradeUI(UpgardeUI ui) { ui.upgradeNameDisplay.transform.parent.gameObject.SetActive(false); // truy xuat vao doi tuong cha } void EnableUpgradeUI(UpgardeUI ui) { ui.upgradeNameDisplay.transform.parent.gameObject.SetActive(true); // truy xuat vao doi tuong cha } public List<WeaponEvolutionBlueprint> GetPossibleEvolution() { List<WeaponEvolutionBlueprint> possibleEvolution = new List<WeaponEvolutionBlueprint>(); foreach (Weapon weapon in weaponSlots) { if (weapon != null) { foreach (PassiveItem catalyst in passiveItemSlots) { if (catalyst != null) { foreach (WeaponEvolutionBlueprint evolution in weaponEvolutions) { if (weapon.currentLevel >= evolution.baseWeaponData.Level && catalyst.passiveItemData.Level >= evolution.catalysPassiveItemData.Level) { possibleEvolution.Add(evolution); } } } } } } return possibleEvolution; } public void EvolveWeapon(WeaponEvolutionBlueprint evolution) { for (int weaponSlotIndex = 0; weaponSlotIndex < weaponSlots.Count; weaponSlotIndex++) { Weapon weapon = weaponSlots[weaponSlotIndex]; if (!weapon) { continue; } for (int catalystSlotIndex = 0; catalystSlotIndex < passiveItemSlots.Count; catalystSlotIndex++) { PassiveItem catalyst = passiveItemSlots[catalystSlotIndex]; if (!catalyst) { continue; } if (weapon && catalyst && weapon.currentLevel >= evolution.baseWeaponData.Level && catalyst.passiveItemData.Level >= evolution.catalysPassiveItemData.Level) { GameObject evolveWeapon = Instantiate(evolution.evolveWeapon, transform.position, Quaternion.identity); WeaponController evolveWeaponController = evolveWeapon.GetComponent<WeaponController>(); evolveWeapon.transform.SetParent(transform); //AddWeapon(weaponSlotIndex, evolveWeaponController); Destroy(weapon.gameObject); // cap nhat lai level va icon // weaponsLevels[weaponSlotIndex] = evolveWeaponController.weaponData.Level; weaponsUISlot[weaponSlotIndex].sprite = evolveWeaponController.weaponData.Icon; // xoa vk dcc tien hoa ra khoi hang cho availableWeapons.RemoveAt(evolveWeaponController.weaponData.EvolvedUpgradeToMove); Debug.LogWarning("EVOLVED"); return; } } } } }
And it is code of spawnweapon:
public void SpawnWeapon(WeaponData weapon) { if (weaponIndex >= inventory.weaponSlots.Count)// co the bang -1 vi list bat dau tu 0 { Debug.LogError("Inventory slots already full"); return; } // Get the type of the weapon we want to spwan Type weaponType = Type.GetType(weapon.behaviour); if(weaponType != null) { GameObject go = new GameObject(weapon.baseStats.name + "Controller"); Weapon spawnedWeapon = (Weapon)go.AddComponent(weaponType); print(weapon.name + " is spawn"); spawnedWeapon.Initialise(weapon); spawnedWeapon.transform.SetParent(transform); // vk la con cua nguoi choi spawnedWeapon.transform.localPosition = Vector2.zero; inventory.AddWeapon(weaponIndex, spawnedWeapon); weaponIndex++; } else { Debug.LogWarning(string.Format("Invalid weapon type for {0}.", weapon.name)); } }
February 23, 2024 at 10:56 am #13393Terence
Keymaster::It looks like your code is a mix of the old system and the new system. Have you watched Part 15? There are parts of the video where you can refer to the new
PlayerInventory
code.February 23, 2024 at 1:25 pm #13395Ngọc Đức Hoàng
Participant::I have seen Part 15 but I’m currently following your stream. The code you run when the stream does not Error, so you can see the above code and fix the error to help me.
February 23, 2024 at 1:50 pm #13396Terence
KeymasterFebruary 23, 2024 at 2:08 pm #13397Ngọc Đức Hoàng
Participant::After clicking the Button, the Spawnweapon () function will be called to spawn the new weapon.and in spawnweapon () have: Inventory.addweapon (Weaponindex, Spawnedweapon); to add weapon.
February 23, 2024 at 11:27 pm #13402Terence
Keymaster::Can you add the following to your
SpawnWeapon()
:public void SpawnWeapon(WeaponData weapon) { print("Weapon spawned: " + weapon.name); if (weaponIndex >= inventory.weaponSlots.Count)// co the bang -1 vi list bat dau tu 0 { Debug.LogError("Inventory slots already full"); return; } // Get the type of the weapon we want to spwan Type weaponType = Type.GetType(weapon.behaviour); if(weaponType != null) { GameObject go = new GameObject(weapon.baseStats.name + "Controller"); Weapon spawnedWeapon = (Weapon)go.AddComponent(weaponType); print(weapon.name + " is spawn"); spawnedWeapon.Initialise(weapon); spawnedWeapon.transform.SetParent(transform); // vk la con cua nguoi choi spawnedWeapon.transform.localPosition = Vector2.zero; inventory.AddWeapon(weaponIndex, spawnedWeapon); weaponIndex++; } else { Debug.LogWarning(string.Format("Invalid weapon type for {0}.", weapon.name)); } }
Then show me your Console window when you add a new weapon.
February 24, 2024 at 12:08 am #13403Ngọc Đức Hoàng
ParticipantFebruary 24, 2024 at 12:10 am #13404Ngọc Đức Hoàng
ParticipantFebruary 24, 2024 at 12:12 am #13405Ngọc Đức Hoàng
ParticipantFebruary 24, 2024 at 12:21 am #13406Terence
Keymaster::I suspect you have multiple copies of some scripts attached. That’s likely what is causing this issue.
Add the following line below the previous print statement and show me the Console:
print( new System.Diagnostics.StackFrame(1, true).GetMethod().Name );
This will tell us which function is calling your SpawnWeapon multiple times.
February 24, 2024 at 12:46 am #13407Ngọc Đức Hoàng
ParticipantFebruary 24, 2024 at 11:45 am #13412Ngọc Đức Hoàng
Participant::I found the error it was in the ApplyupGradeOptions (): IF (! Islevelup) must be removed from the For loop. Thanks for your help
-
AuthorPosts
- You must be logged in to reply to this topic.
Advertisement below: