Say I have a script that is assigned to every projectile, now I want to be able to say
proj = Instantiate(bullet, transform.position, aimDirection);
and then I want to be able to set the stats of the projectile in a way similair to proj.getcomponent<ScriptName>().stats = selectedWeapon.stats;
Where selectedWeapon
is one out of a List
of weapons.
How should I implement this? I think it will come down to either a struct or a class, but what do you think?
I think that duplication of weapon stats is not really necessary. I will give a simple implementation of the weapon and projectile classes, as I see them
using UnityEngine;
[CreateAssetMenu(menuName = "SO/new WeaponStats", fileName = "WeaponStats")]
public class WeaponStats : ScriptableObject
{
[SerializeField] private float _damage;
public float Damage => _damage;
[SerializeField] private float _cooldown;
public float Cooldown => _cooldown;
}
public class Weapon : MonoBehaviour
{
[SerializeField] private Bullet _bulletPrefab;
[SerializeField] private WeaponStats _weaponStats;
//Or any other logic
public float DealDamage()
{
return _weaponStats.Damage;
}
public void Shoot()
{
Bullet bullet = Instantiate(_bulletPrefab, transform.position, Quaternion.identity);
bullet.Init(this);
/*
* ...
*/
}
}
public class Bullet : MonoBehaviour
{
private Weapon _weapon;
public void Init(Weapon weapon)
{
_weapon = weapon;
}
//Or any other method or event
private void OnCollisionEnter(Collision collision)
{
_weapon.DealDamage();
}
}