- Home /
Identifying Prefabs without using strings?
I've been reading 50 Tips for Working with Unity (Best Practices) and best practice #34 confused me.
34) Don’t use strings for anything other than displayed text. In particular, do not use strings for identifying objects or prefabs etc. One unfortunate exception is animations, which generally are accessed with their string names.
How is it possible to access objects and prefabs without using strings (for their names)?
I know there's tags and types, but I've heard they're slow.
Answer by Loius · May 02, 2013 at 03:39 AM
It's difficult to describe, but your objects should 'already know' what they need to know. Rule 34 (bahaha) should really be considered more of a guideline, since there are certain things that can only be done via string access.
Does your player have a gun? Don't find it by name. Find it by relation. Your player should have a gun variable anyway; assign it in the inspector or during runtime when you create/swap to that gun.
If you use a string for something, it'll be slower than a direct reference and harder to debug/maintain your code. Unity can help with references but if you change an object name and forget to change it in code, the entire universe will implode.
I just got the Rule 34 reference, haha.
You mention assigning it in the inspector. The 50 tips article seems to swing between "Don't do anything in the inspector" and "When you set this link up in the inspector". Setting up links in the inspector seems kind of prone to failure. But the only alternative all I can think of is GameObject.Find("OtherThing") in our original object's Start() function.
Not really sure how the inspector could fail, it's just making it easy on yourself :P
I don't really see anywhere they're saying not to use the inspector, it's really pretty great.
Your answer
Follow this Question
Related Questions
Using Resources.load with a variable 1 Answer
String to prefab 1 Answer
Reusing tilemap segments 0 Answers
How can I make prefabs that don't break when models change? 1 Answer