I'm trying to get the position of items in the game world and render them onto the screen. I've managed to get this working, however I seem to be running into major performance issues when ever I enable this feature. I am losing about 40-50 fps. I have a feeling this is related to iterating through the array doing the transformation within the OnGUI() life cycle method which is called multiple times a frame, however I'm not entirely sure. Any pointers would be appreciated, I'm still very new to game development.
Code in question:
private void OnGUI()
{
if (showItems)
{
DrawLoot();
}
if (showItems && Time.time >= itemNextUpdateTime)
{
lootItems = UnityEngine.Object.FindObjectsOfType<LootItem>();
itemNextUpdateTime = Time.time + itemUpdateInterval;
}
}
Draw Method:
public void DrawLoot()
{
foreach (LootItem item in lootItems)
{
if (item == null || item.name == null || item.name == string.Empty)
{
continue;
}
var pos = Camera.main.WorldToScreenPoint(item.transform.position);
float itemDistance = Vector3.Distance(Camera.main.transform.position, item.transform.position);
Vector3 vector = new Vector3(pos.x, pos.y, pos.z);
if (itemDistance <= maxLootDrawingDistance && vector.z > 0.01)
{
string itemLabel = $"{item.Item.ShortName.Localized()} - {itemDistance}";
GUI.Label(new Rect(vector.x - 50f, Screen.height - vector.y, 100f, 50f), itemLabel);
}
}
}
||
, not&&
— an item cannot simultaneously benull
and have aname
field. \$\endgroup\$