- Home /
Struct for holding Class Parameters
Hello everyone,
Recently I've been trying to optimize my game a little bit. What is performance wise best way of using structs?
I tried to store my class parameters to separate structs? Will this make any difference to my game performance? Thank you.
I wrote this sample script to showcase on how I used structs in my scripts.
Old Script:
using UnityEngine;
public class SampleScript : MonoBehaviour {
[SerializeField] bool canZoom;
[SerializeField] float zoomFOV;
[SerializeField] float smooth;
Camera mainCam;
float defaultFOV;
void Start ()
{
mainCam = Camera.main;
defaultFOV = mainCam.fieldOfView;
}
void Update ()
{
AimZoom();
}
private void AimZoom ()
{
if (Input.GetMouseButton(1))
{
if (!canZoom) return;
mainCam.fieldOfView = Mathf.Lerp(mainCam.fieldOfView, zoomFOV, Time.deltaTime * smooth);
}
else
{
mainCam.fieldOfView = Mathf.Lerp(mainCam.fieldOfView, defaultFOV, Time.deltaTime * smooth);
}
}
}
New Script:
using UnityEngine;
struct Parameters
{
public bool canZoom;
public float zoomFOV;
public float smooth;
}
public class SampleScript : MonoBehaviour {
[SerializeField] Parameters parameters = new Parameters();
Camera mainCam;
float defaultFOV;
void Start ()
{
mainCam = Camera.main;
defaultFOV = mainCam.fieldOfView;
}
void Update ()
{
AimZoom();
}
private void AimZoom ()
{
if (Input.GetMouseButton(1))
{
if (!parameters.canZoom) return;
mainCam.fieldOfView = Mathf.Lerp(mainCam.fieldOfView, parameters.zoomFOV, Time.deltaTime * parameters.smooth);
}
else
{
mainCam.fieldOfView = Mathf.Lerp(mainCam.fieldOfView, defaultFOV, Time.deltaTime * parameters.smooth);
}
}
}
This really won't have any effect to performance.
Yeah, you're not going to notice anything with a change like this. It's more likely that the introduction of structs for this specific situation (monitoring all exposed fields) will just complicate things.
It's good to keep performance in $$anonymous$$d, but have you noticed any performance issues that you feel must be addressed? It's my experience that premature optimization leads to way more headaches down the road than readable, negligibly-"slower" code ever will.
Your answer
Follow this Question
Related Questions
How to make classes/structs public to all scripts 0 Answers
Best way to calculate sum of custom object holding numbers and returning sum as that object instance 0 Answers
All Arrayinstances get changed -1 Answers
Multiple Cars not working 1 Answer
How -exactly- do classes and structs work in Unity? 0 Answers