Safely Check and Access Components with TryGetComponent
Calling GetComponent<T>() inside conditional checks or update loops can lead to unnecessary overhead or NullReferenceException risks.
The Tip: Calling GetComponent<T>() inside conditional checks or update loops can lead to unnecessary overhead or NullReferenceException risks.
How to Use: Use TryGetComponent<T>(out var component). It returns a bool indicating component existence while assigning the output variable cleanly without allocating garbage.
using UnityEngine;
public class Interaction : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out IDamageable damageable))
{
damageable.TakeDamage(25);
}
}
}
Article complete?
20 XP lands automatically when you reach the end, and it counts toward today's quests.
Next level
Shader Graph Basics for 2D GamesGame Dev Articles · 1 min · +20 XPRate this article
Comments
Comments are held for moderation before appearing publicly.