Hi there, first post.
I set up a way to assign a damage value to fired/instantiated projectiles from a parent object’s gun scriptable object - which holds that data. It’s functional, but my spidey-senses tell me that it’s very much a beginner/poor-man’s-solution. I’m looking for a way to optimize it.
Here’s the general architecture:
*Each weapon’s gun Scriptable Object (gunSO) is attached to a “CurrentWeapon” script via each weapon’s prefab. “CurrentWeapon” manages things like shoot, zoom, and reload from the player’s inputs.
*In a child object (the gun), there’s a “WeaponFunctions” script, which takes inputs to its public methods from the gunSO assigned to “CurrentWeapon” to actually Raycast/launch projectiles/etc (i.e., interact with the world based on what the CurrentWeapon’s gunSO says it can/can’t do).
*Instantiated projectiles have a “Projectile” script attached which has the damage value and OnTriggerEnter functions.
Here’s the relevant code which I’m sure can be optimized (irrelevant code like animations, particles, timeSinceLastShot, referencing inputs, etc., has been omitted):
In “CurrentWeapon” script:
GunSO thisGunSO;
WeaponFunctions thisGun
void Start()
{
// new weapon is made and the WeaponFunctions component is grabbed from it & referenced
}
void HandleShoot()
{
thisGun.Shoot(thisGunSO)
}
In “WeaponFunctions” Script:
public void Shoot(GunSO gunSO)
{
HandleShootType(gunSO);
}
void HandleShootType(GunSO gunSO)
{
if (gunSO.Raycast)
{
HandleShootRaycast(gunSO);
}
if (gunSO.Projectile)
{
HandleShootProjectile(gunSO);
}
}
void HandleShootProjectile(GunSO gunSO)
{
// code to calculate spawn point & target point, etc.
GameObject currentProjectile = Instantiate(gunSO.projectilePrefab, attackPoint.position, Quaternion.identity);
Projectile projectileScript = currentProjectile.GetComponent<Projectile>();
projectileScript.AssignDamage(gunSO.damage);
// Grabs the "Projectile" code from the instantiated projectile
// code to add force & direction to the projectile
}
In “Projectile” Script:
public int assignedDamage = 0;
void Start()
{
AssignDamage(assignedDamage);
}
void OnTriggerEnter(Collider other)
{
// code to deal damage equal to "assignedDamage"
}
public void AssignDamage(int amount)
{
assignedDamage = amount;
}
Let me know how badly I did, haha.
Also let me know if I need to clarify anything because it’s a lot.
I suppose this also opens up a larger question about the architecture of the weapons - should any of these methods be in the gunSO script? Could anything be called from a more optimized place? Or would it make no difference?
Thanks!