I'm really struggling with creating a weapon/item unlock system via an in-game shop. The player should only be able to select weapons at indexes that have been unlocked or bought.
I've wasted two days on the best way to achieve this and I'm still not anywhere near a solution.
Currently this is what I have:
I have a WeaponUnlock
script that handles a dictionary
of weapons and another WeaponSwitcher
script that access vales from that script to check if it is unlocked or not.
public class WeaponUnlockSystem : MonoBehaviour
{
private Dictionary<string, bool> weaponUnlockState;
void Start()
{
// Seeding with some data for example purposes
weaponUnlockState = new Dictionary<string, bool>();
weaponUnlockState.Add("Shotgun", true);
weaponUnlockState.Add("Rifle", true);
weaponUnlockState.Add("FireballGun", false);
weaponUnlockState.Add("LaserGun", false);
weaponUnlockState.Add("FlamethrowerGun", false);
weaponUnlockState.Add("SuperGun", false);
}
public bool IsWeaponUnlocked(string weapon_)
{
if (weaponUnlockState.ContainsKey(weapon_))
return weaponUnlockState[weapon_]; // this will return either true or false if the weapon is unlocked or not
else
return false;
}
public void UnlockWeapon(string weapon_) //this will be called by the button..
{
if (weaponUnlockState.ContainsKey(weapon_))
weaponUnlockState[weapon_] = true;
}
}
The WeaponSwitcher
gets the name of the weapon from the nested children every time the nextWeapon
button is pressed:
weaponName = this.gameObject.transform.GetChild(weaponIdx).name.ToString(); //get the name of the child at current index
if (weaponUnlock.IsWeaponUnlocked(weaponName)) //ask weaponUnlockSystem if this name weapon is unlocked or not, only enable the transform if true is returned
selectedWeapon = weaponIdx;
This...... works..... but I know is not practical. As the script sits on a game object and at every time it is called the Start()
is called that will reset all the unlocked values. Also will I have to make it persistent via DontDestroyOnLOad()
through scenes?
I can get use PlayerPrefs
and set a value for every weapon, but that is also not ideal and also to avoid it being reset every time someone opens my game I would have to perform a checks of PlayerPrefs.HasKey()
for every weapon. Also not practical.
There must be a better way of doing this. Its funny that I cannot find much help online for this and dont know how everyone is getting around this.
Thanks