I'm aware locally declared variables get compiled out into essentially the same code as per the StackOverflow answer here. However, it doesn't cover creating and using static objects, especially Unity objects. My knowledge of C# is ad hoc coming from C++ and just jumping straight into Unity, and past practices sees me using temp variables instead of nicely named ones. I want to use better practices for my next project where readability is obviously valuable but performance moreso. So consider these two pieces of code...
With static temps...
public class Shot : MonoBehaviour {
static Actor tempActor;
static Vector3 tempVec;
static float tempFloat;
static HitResult hitResult;
public float damage;
public float unblockable;
public Vector3 originationPoint;
private void OnTriggerEnter(Collider collision) {
if (collision.gameObject.layer == 11) {
tempActor = collision.gameObject.GetComponent<Actor>();
if (tempActor != null) {
tempVec = collision.transform.position - originationPoint;
// cast ray
originatorActor.RayDisableColliders();
bool rayHit = Physics.Raycast(originationPoint, tempVec, out hitResult, range, 1<<11, QueryTriggerInteraction.Ignore);
if (rayHit) {
if (hitResult.collider.gameObject.CompareTag("Hero") || hitResult.collider.gameObject.CompareTag("Villain")) {
tempActor = hitResult.collider.gameObject.GetComponent<Actor>();
tempActor.HitByShot(class_utilities.GetAngle(hitResult.transform, originationPoint), damage, unblockable);
}
}
originatorActor.RayEnableColliders();
}
}
}
}
With locally declared temps
public class Shot : MonoBehaviour {
public float damage;
public float unblockable;
public Vector3 originationPoint;
private void OnTriggerEnter(Collider collision) {
if (collision.gameObject.layer == 11) {
Actor tempActor = collision.gameObject.GetComponent<Actor>();
if (tempActor != null) {
Vector3 offset = collision.transform.position - originationPoint;
// cast ray
originatorActor.RayDisableColliders();
HitResult hitResult;
bool rayHit = Physics.Raycast(originationPoint, offset, out hitResult, range, 1<<11, QueryTriggerInteraction.Ignore);
if (rayHit) {
if (hitResult.collider.gameObject.CompareTag("Hero") || hitResult.collider.gameObject.CompareTag("Villain")) {
tempActor = hitResult.collider.gameObject.GetComponent<Actor>();
tempActor.HitByShot(class_utilities.GetAngle(hitResult.transform, originationPoint), damage, unblockable);
}
}
originatorActor.RayEnableColliders();
}
}
}
}
Is there any difference in terms of performance, notably to my mind memory allocation and garbage collection, between the two approaches?