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?
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?