Skip to content

Instantly share code, notes, and snippets.

@fuqunaga
Last active June 9, 2022 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fuqunaga/b3ff5572df15d7e9499494ea9a748d3f to your computer and use it in GitHub Desktop.
Save fuqunaga/b3ff5572df15d7e9499494ea9a748d3f to your computer and use it in GitHub Desktop.
Comparison of GetComponent() and TryGetComponent()
using UnityEngine;
public class SampleComponent : MonoBehaviour
{
public int value;
}
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Profiling;
public class TestTryGetComponent : MonoBehaviour
{
public int count = 1000;
public bool hasComponent;
private readonly List<GameObject> _goList = new();
void Start()
{
GenerateGameObjects();
}
void GenerateGameObjects()
{
for (var i = 0; i < count; ++i)
{
var go = new GameObject(i.ToString());
if (hasComponent)
{
go.AddComponent<SampleComponent>();
}
go.transform.SetParent(transform);
_goList.Add(go);
}
}
void Update()
{
Profile_GetComponent();
Profile_TryGetComponent();
}
void Profile_GetComponent()
{
Profiler.BeginSample(nameof(Profile_GetComponent));
for (var i = 0; i < count; ++i)
{
var sampleComponent = _goList[i].GetComponent<SampleComponent>();
if (sampleComponent != null)
{
sampleComponent.value++;
}
}
Profiler.EndSample();
}
void Profile_TryGetComponent()
{
Profiler.BeginSample(nameof(Profile_TryGetComponent));
for (var i = 0; i < count; ++i)
{
if (_goList[i].TryGetComponent<SampleComponent>(out var sampleComponent))
{
sampleComponent.value++;
}
}
Profiler.EndSample();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment