This example showcases a PlayerController detecting collisions with an Enemy and retrieving its component. The bad practice uses GetComponent(), causing unnecessary memory allocations, while the good practice replaces it with TryGetComponent(), optimizing performance and reducing overhead in frequent collision checks. 🚀
Last active
February 6, 2025 22:13
-
-
Save aryan-saxena-outscal/d2df24abde243789aefd5e85f81b6e8d to your computer and use it in GitHub Desktop.
This file contains 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 BadPlayerController : MonoBehaviour | |
{ | |
private void OnCollisionEnter(Collision collision) | |
{ | |
Enemy enemy = collision.gameObject.GetComponent<Enemy>(); | |
if (enemy != null) | |
{ | |
TakeDamage(enemy.GetDamage()); | |
} | |
} | |
private void TakeDamage(int damage) | |
{ | |
Debug.Log($"Player took {damage} damage!"); | |
} | |
} | |
public class Enemy : MonoBehaviour | |
{ | |
public int GetDamage() => 10; | |
} |
This file contains 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 GoodPlayerController : MonoBehaviour | |
{ | |
private void OnCollisionEnter(Collision collision) | |
{ | |
if (collision.gameObject.TryGetComponent<Enemy>(out Enemy enemy)) | |
{ | |
TakeDamage(enemy.GetDamage()); | |
} | |
} | |
private void TakeDamage(int damage) | |
{ | |
Debug.Log($"Player took {damage} damage!"); | |
} | |
} | |
public class Enemy : MonoBehaviour | |
{ | |
public int GetDamage() => 10; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment