Hi!
I’m new here in Unity forums and quite new at scripting. I’m creating a small mobile shoot em up game and I have troubles getting its weapon system working properly. Intention is to create it so that the player object has a script that has “weapon slots” and when player collects a new weapon these weapon slots would fill (and if slots are full weapons are upgraded) and instantiates collected weapon for the player.
So far I’ve made a script that has an array of game objects for weapon slots. And a function that instantiates objects from the array to as a child object. That itself is somewhat working, but the logic that determines, is the slot (element in the weaponSlot array) empty or not isn’t working, and such creating a problem that when collecting a new weapon and calling the CreateWeapon() function it instantiates all the weapons again and again.
I’ve tried also too many “bubblegum fixes” so that it’s a bit messy script overall now.
I’d like to know how I could create better system for this? I know that there might be many ways to do this, but if anyone could help me to find a good (enough) one, it would help a lot!
so to summarize, help me find a good way to create a weapon slot system for the player, that recognizes if the slot is empty or not (if a slot full, look for an empty slot or if all slots are full, use upgrading function) and making sure that it’s instantiating the weapon only once.
And I’m using C#, so code answers with that.
This is what the CreateWeapon function looks now (I know it’s bad, very bad, horrible).
I know that somehow this could be much more fluent and not so badly laid out, but I’m not sure how.
Please help me out.
public void CreateWeapon()
{
if(weaponSlots[0] != null && isSlot1Taken == false)
{
GameObject obtainedWeapon = null;
GameObject primaryWeapon = weaponSlots[0];
if(obtainedWeapon != null)
{
Debug.Log ("weapon slot full");
return;
}else
{
obtainedWeapon = Instantiate (primaryWeapon, transform.position, transform.rotation) as GameObject;
obtainedWeapon.transform.parent = gameObject.transform;
isSlot1Taken = true;
}
}else{
Debug.Log ("Weapon Slot01 Full");
return;
}
if(weaponSlots[1] != null && isSlot2Taken == false)
{
GameObject obtainedWeaponA = null;
GameObject obtainedWeaponB = null;
GameObject secondaryWeapon = weaponSlots[1];
Vector3 barrelPos = new Vector3(0.0f,1.0f,0.0f);
if(obtainedWeaponA != null && obtainedWeaponB != null)
{
Debug.Log ("weapon slot full");
return;
}else
{
obtainedWeaponA = Instantiate (secondaryWeapon, transform.position + barrelPos, transform.rotation * Quaternion.Euler(0, 0, 15)) as GameObject;
obtainedWeaponA.transform.parent = gameObject.transform;
obtainedWeaponB = Instantiate (secondaryWeapon, transform.position + -barrelPos, transform.rotation * Quaternion.Euler(0, 0, -15)) as GameObject;
obtainedWeaponB.transform.parent = gameObject.transform;
isSlot2Taken = true;
}
}
}