Just wondering if there are any disadvantages to assigning components/objects through the UI vs finding them in code. Will they misbehave in any way? I read some threads from back in the day saying you can lose the assignments etc but is this still the case?
Is there a best practice?
Thanks
1 Like
I had the exact same question back in the day. There are differences in each approach but they are minor:
UI assignment benefits:
- No performance cost since Find() and GetComponent() methods are avoided
- Good for variables that reference only a single object
UI assignment flaws:
- Can get really messy in the inspector
- References to that object can get lost (for example if you change the name of the variable, all references are lost)
Code assignment benefits:
- If used inside of the Awake(), Start(), OnEnable(), etc. has really small performance cost that will usually go unnoticed.
- Good for changing references (Since at that point you have to use GetComponent() or Find() anyway).
Code assignment flaws:
- If used inside of the Update() or any similar method, can cause performance issues.
There are some other tiny details to mention here and there, but this is mostly all there is to it. Basically, use both, but just keep in mind the points I mentioned here.
6 Likes
I prefer code assignment when working with dynamic structures, for example some prefab instantiated and some other object needs to reference it and insprector assignmetn whenever structure is static.
3 Likes
Also, assigning things in the editor only works for instances that are both either in the same scene, or the same prefab.
Additionally, inspector assignment means the reference is assigned from the very beginning, so you never run into an issue of needing the reference in another script before the reference has been set.
Sometimes you just can’t set a reference in the inspector though, and must do it through code.
1 Like