- Home /
What is better : every frame reassigne value or use if statement?
I appropriate text value of UI element Text in Update , but can apply if-statement to not to do it every frame . What is better solution?
Answer by Captain_Pineapple · Feb 21 at 05:17 PM
I'd choose option C:
Don't do stuff like this in Update at all. Both ways clutter your code and take up performance. Something like setting some text on the UI should be done when it needs to be done.
Example: You want to update the amount of lives you have and have a text ui element that says "3 Lives".
From what i understand what you currently do is every update write healthLabel.text = currentlives.ToString() +" Lives"
.
Instead you should have a function which does this and is called only when your lives actually get changed. This would be the proper way to do it.
@Captain_Pineapple Yes , but I have something like this :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InteractionController : MonoBehaviour
{
RaycastHit hit;
[SerializeField] LayerMask interactableLayer;
[SerializeField] Text hintText;
public static string SelectedObject;
// Update is called once per frame
void Update()
{
if(Physics.Raycast(transform.position, transform.forward, out hit, 5, interactableLayer))
{
hintText.text = hit.transform.gameObject.name;
IInteractable interactable = hit.transform.gameObject.GetComponent<IInteractable>();
if(Input.GetKeyDown(KeyCode.F))
{
interactable.Interact();
}
}
else
{
hintText.text = "";
}
}
}
When I interact with object , I want to display it's name (actually not only name , but it doesn't matter). And if I don't interact with any object , I set text empty(or disable Text object). So what shoud I do in such situation?
aah, fair point :)
In this situation, i'd just leave it like this. You should optimize single instances of something like this if you specifically know that they slow down your game significantly. Otherwise these kind of micro-optimizations just take up the time you could spend better elsewhere.
If you specifically want a really really small improvement then introduce a flag isTextEmpty
that you check before setting the name empty. I'd not do something like this in your interactable name setting part as you'd have to check if the object has changed which takes up the same amount of performance needed to simply set the text.
As a sidenode: Later on if you do string concatenations here you might wanna revisit this with the profiler on. String concat always creates memory allocations which might be bad if done every frame.
Your answer
Follow this Question
Related Questions
Using multiples of 360 in if statements. 2 Answers
IF doesn't work 3 Answers
C# if-statement optimization 1 Answer
Checking a GUI.Textfield (C#) 1 Answer