Last active
June 9, 2022 06:52
-
-
Save fuqunaga/b3ff5572df15d7e9499494ea9a748d3f to your computer and use it in GitHub Desktop.
Comparison of GetComponent() and TryGetComponent()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class SampleComponent : MonoBehaviour | |
{ | |
public int value; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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