I tried your suggestion, and while it is less spaghetti it still generates 400B of GC which is better than 0.8 kB with the coroutine! Thank you.
The worry now is since I am checking if the desired value is == 0, is MoveTowards prone to miscalculating the float, like never reaching exactly 0? Would it be a good idea to use Mathf.Approximately ?
I’m not quite seeing why there’s GC going on, unless it’s TMP being bad. You should put the profiler in deep mode and figure out what’s up. Also probably test in builds, might be some editor only stuff.
Unsolicited code review time!
The currentOutline = desiredOutline; there isn’t necessary, you already checked that it had that value!
For fun, if you want to, you can code-golf the entire thing down to:
if (currentOutline == desiredOutline)
desiredOutline = baseDesiredOutline - currentOutline;
Since x - 0 = x and x - x = 0
Though it makes you have to think more about the code when you read it than you used to have.
Each call to the generator method FadeInOutCoroutine creates a new state machine object which is returned. If everything would be implemented in a single endless running coroutine, there would be no problem
No, the code I posted in the above link actually does not generate GC.
The only lines of code are:
variable declarations
a variable assignment using a static Mathf.MoveTowards() method
whatever you do with the output value (currentQuantity)
It’s likely something else you are doing or that TMPro is doing. It’s possible TMPro rebuilds the mesh when you change the fade color for all I know.
Been using Unity in production code for a decade, and generally as long as you don’t do needless things, GC is NEVER an issue. Worrying about GC and such is a complete waste of time 99.99% of the time. Just don’t do needless thigns.
Hi, again and thank you all. This code below is the final version and generates 0 GC. It was a TMP issue and if you would like to read on it more here is the link of the discussion:
public float desiredOutline;
public float fadeTime;
private float currentOutline = 0;
private TextMeshProUGUI objectTMP;
private Material tmpMaterial;
private float baseDesiredOutline;
private bool hasReachedMax = false;
private void Awake()
{
baseDesiredOutline = desiredOutline;
objectTMP = gameObject.GetComponent<TextMeshProUGUI>();
tmpMaterial = objectTMP.fontMaterial;
}
void Update()
{
if (hasReachedMax == false)
{
objectTMP.UpdateMeshPadding(); // Update padding until max
}
if (currentOutline == desiredOutline)
{
if(hasReachedMax == false) // When max update one last time
{
objectTMP.UpdateMeshPadding();
hasReachedMax = true;
}
desiredOutline = baseDesiredOutline - currentOutline; // Fade the outline opposite direction
}
currentOutline = Mathf.MoveTowards(currentOutline, desiredOutline, fadeTime * Time.deltaTime);
tmpMaterial.SetFloat(ShaderUtilities.ID_OutlineWidth, currentOutline); // Use material instance to avoid GC
}