r/UnityHelp • u/[deleted] • Dec 21 '21
When to use Referances and when to use GameObject.FindWithTag()?
I'm just starting out and this question really bothers me. Sure, there are times where only the GameObject.FindWithTag() works, for example if you have mutiple 'players' and want to switch between them or you delete them and then spawn them again. Then a reference would not work. But what is the 'best case' for all the other situation. Is it advised to use References whenever possible or is it smarter to just create a Tag for every object that you want to refer to in your C# code?


Are there public resources on this? Or is there a completely different approach to this?
3
Upvotes
1
u/MischiefMayhemGames Dec 22 '21
Speaking from personal experience references are better, I do not think I have used tags in quite a while. Finding tags is (comparatively) slow and on occasion can be messed up in source control.
In terms of the spawning and deleting objects in your example that can be done with references also, just with a slightly different architecture. For example you can use some kind of object pool, or if you want to fully destroy the objects have an additional reference to a spawner and make use of null checks.
For example with the spawner you might have something like
public Spawner spawner;
public Transform Player;
if(Player == null)
{
Player = spawner.GetNewPlayer().transform;
}