Back for round two? Good. I hope you've read the previous article.
If Part 1 covered TryGetComponent & friends, this batch is about the stuff that happens around your components like tags, cameras, and the Inspector itself quietly judging your field values.
Same thing as before: five more practical Unity coding techniques for beginners, real code and no fillers.
Let's begin!
Why More Unity Coding Techniques for Beginners Are Worth Digging Into
Solo dev life means you don't get a code review. Nobody's going to catch the Camera.main call you left inside Update() or the string comparison quietly generating garbage sixty times a second. These five tricks exist specifically to catch the mistakes nobody's around to point out for you.
None of them really require a redesign. Most are just a one-line change.
1. Use CompareTag() Instead of gameObject.tag
This one looks completely harmless, and that's exactly the problem:
// Instead of:
if (gameObject.tag == "Enemy")
{
TakeDamage();
}
Here's the interesting thing: gameObject.tag returns a new copy of the string, not a reference.
== however compares two strings, repeated every frame, for every collision check, tiny garbage allocation, over and over, until your GC decides now's a great time to pause your game mid-boss-fight.
CompareTag() skips the allocation entirely by comparing internally, under the hood, without handing you a throwaway string copy:
// Same result, no garbage
if (gameObject.CompareTag("Enemy"))
{
TakeDamage();
}
It's not going to matter for one comparison. It absolutely matters when you're checking tags in OnCollisionEnter across a screen full of bullets and enemies. Free performance, zero downside!
2. Cache Camera.main in Unity Instead of Calling It Every Frame
Camera.main feels like a simple property. It is not. Under the hood, it's doing a scene search for a GameObject tagged "MainCamera", and if you're calling it inside Update(), you're paying that cost every single frame, for no reason, since your main camera almost never changes mid-game.
// Bad: searches the scene every frame
void Update()
{
Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position);
}
The fix is embarrassingly simple; cache Camera.main in Unity once, then reuse it:
private Camera mainCamera;
void Awake()
{
mainCamera = Camera.main;
}
void Update()
{
Vector3 screenPos = mainCamera.WorldToScreenPoint(transform.position);
}
One lookup in Awake(), done. If you genuinely need to handle the camera changing at runtime (cutscenes, camera switching, whatever), re-cache it when that happens instead of going back to calling Camera.main on repeat. Caching Camera.main in Unity is one of those changes that costs you nothing and just quietly makes your game faster.
3. [RequireComponent(typeof(T))]
I use this one all the time, because in all the excitement I often forget. Ever attach a script that assumes a Rigidbody exists, forget to actually add the Rigidbody, and spend ten minutes confused about why nothing's moving? [RequireComponent] is there to stop that from happening:
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
private Rigidbody rb;
private void Awake()
{
rb = GetComponent<Rigidbody>(); // guaranteed to be there
}
}
Attach PlayerMovement to a GameObject with no Rigidbody and Unity automatically adds one for you. If you try to remove the Rigidbody afterward while the script's still attached then Unity blocks it. The dependency is baked into the script itself instead of living in your memory (which, let's be honest, is already full of other things).
It won't replace every null check you write, but for "this component genuinely cannot function without that one," it's a clean, self-documenting guarantee.
4. Null-Coalescing Assignment (??=) for Lazy Component Caching
You know the drill: cache a component reference in Awake() so you're not calling GetComponent() repeatedly. But sometimes you don't want to front-load every cache call in Awake(), you just want it fetched the first time it's actually needed.
That's what ??= is for. It assigns a value only if the variable is currently null:
private Rigidbody rb;
private void Jump()
{
rb ??= GetComponent<Rigidbody>();
rb.AddForce(Vector3.up * jumpForce);
}
First call to Jump(): rb is null, so it fetches the component and caches it. Every call after that: rb already has a value, so the assignment is skipped entirely and you go straight to using it. It's a lazy-loading pattern in a single line, without writing out a full if (rb == null) { rb = GetComponent<Rigidbody>(); } block every time you need this behavior.
5. Use LayerMasks to Filter Physics Queries
The best angle isn't simply "LayerMasks exist", it's showing how they eliminate ugly layer checks and let the Inspector control what your code interacts with.
Instead of:
if (hit.collider.gameObject.layer == 6 ||
hit.collider.gameObject.layer == 7 ||
hit.collider.gameObject.layer == 8)
{
// Do something
}
You could use a LayerMask and let the Inspector decide which layers should be included:
[SerializeField] private LayerMask targetLayers;
if (((1 << hit.collider.gameObject.layer) & targetLayers) != 0)
{
// Do something
}
But there's an even better example for beginners: pass the LayerMask directly into the physics query.
[SerializeField] private LayerMask enemyLayers;
private void Update()
{
if (Physics.Raycast(
transform.position,
transform.forward,
out RaycastHit hit,
100f,
enemyLayers))
{
Debug.Log("Hit an enemy!");
}
}
Now the code doesn't need to ask what it hit. The physics query itself asks: "only notify me about the objects in these layers."
You can then use the Inspector to select the different layers and adjust them without touching the code!
Wrapping Up These Unity Coding Techniques for Beginners (Again)
Tags, cameras, required components, lazy caching, and LayerMasks — none of it's glamorous, but that's kind of the point. These are the small, boring fixes that quietly prevent the big, annoying bugs.
Grab one you haven't used yet and drop it into your project today. Combined with Part 1, that's ten small upgrades to your Unity coding habits, and ten fewer ways for future-you to get blindsided.
Happy coding!
```
No comments:
Post a Comment