I am just starting to get a hand on memory management, and this question I haven’t luck yet to find be answered clearly.
So in short, which implementation is better to produce less garbadge and optionally be more performant:
public class Damager: MonoBehaviour
{
private float dps = 1;
void Update()
{
if(Physics.Raycast(transform.position, transform.forward, out RaycastHit hit))
{
Idamagable target = hit.collider.gameObject.GetComponent<Idamagable>();
if (target != null)
{
target.getDamage(dps * Time.deltaTime);
}
}
}
Or
public class Damager: MonoBehaviour
{
private float dps = 1;
private Idamagable cachedtarget;
private RaycastHit cachedhit;
void Update()
{
if(Physics.Raycast(transform.position, transform.forward, out cachedhit))
{
cachedtarget = cachedhit.collider.gameObject.GetComponent<Idamagable>();
if (cachedtarget != null)
{
cachedtarget.getDamage(dps * Time.deltaTime);
}
}
}