Thanks for checking out my question, I have a gun script that is attached to the player with variables that I want to change depending on which gun the player is holding. I only have one gun implemented so far but want to add more and the current way I am exchanging the variables is pretty ugly and long. I am not sure what the best way of doing this but my best guess is to make a script only containing variables on the weapon model, and on a weapon switch load those into the gun script. But I would like to hear any better or more efficient ways of exchanging variables. Thanks for your time.
I think you’d really like Scriptable Object’s. Brackeys has an amazing video on this that really puts it all in plain English too.
If those don’t float your boat, I would also suggest trying out a Strategy Design Pattern . The purpose of this is to provide an easy way to make many things that do the same thing, differently. In plain English: QuickSort and MergeSort both sort a list, but they go about doing it differently. In your case, SMG and Pistol both fire bullets, but may deal damage differently.
To get you started with a basic Strategy Pattern:
IWeapon.cs
//you'll want an interface as the main type to allow you to swap out the damage of guns.
public Interface IWeapon {
//gets and sets the damage the weapon deals.
public float getDamage();
public void setDamage(float damage);
//gets and sets the rate of fire
public float getRateOfFire();
public void setRateOfFire(float rate);
//gets and sets for whether the weapon is automatic.
public bool getIsAutomatic();
public void setIsAutomatic(bool isAuto);
}
Now, lets create a base weapon type that contains the relevant info for a pistol:
Pistol.cs
public class Pistol : IWeapon {
// because this implements the IWeapon interface, you also need to include all its methods.
float damage = 10;
float rateOfFire = 15;
bool isAuto = false;
public float getDamage() {
return this.damage;
}
public void setDamage(float damage){
this.damage = damage;
}
//gets and sets the rate of fire
public float getRateOfFire(){
return this.rateOfFire;
}
public void setRateOfFire(float rate){
this.rateOfFire = rate;
}
//gets and sets for whether the weapon is automatic.
public bool getIsAutomatic(){
return this.isAuto;
}
public void setIsAutomatic(bool isAuto) {
this.isAuto = isAuto;
}
}
When you want to create say, SMG or Rifle now, all you need to do is implement the IWeapon interface.
To use these, a quick code snippet would be like so:
public IWeapon weapon = new Pistol();
public Animator playerPoses;
public gameObject weaponModel;
public someShootingScript _shootingScript; //the actual script that shoots the gun and has the damage per bullet.
void Start() {
_shootingScript.setModelAndAnimator(weaponModel, playerPoses);
_shootingScript.setDamage(weapon.getDamage());
//... and so on
}
void changeToWeapon(Animator pose, GameObject model, IWeapon weapon) {
//pretty much just repeat Start()
}
I hope this helps!