- Home /
Is there common way of accessing scene/script objects?
Hello,
Unity has lots of ways to acces a scene or script object from C# script. (Here are some examples which i like to use)
GameObject.Find("Name"); //Accessing via Name/Tag/By Type
[serialized Field] private GameObject //Accessing via Inspector
Store Instance of Object in a Singleton, to make it accessable for others.
Questions:
Is there common way of accessing objects?
Does one has disadvantages over the others?
What does happen to the [serialzed Field] properties if you build/release your game? (Does it still work without the Inspector?)
Answer by Deathdefy · Nov 09, 2018 at 07:51 PM
The ways you outlined above are the most common in Unity. They expose a bunch of different ways to find your objects/components/etc at runtime. Using those obviously has a cost as they have to go through your scene hierarchy and find what you are looking for. If you need to find objects at runtime try to minimize the amount you need to find by setting the references directly in the inspector prior to making a build. If you prefer to find objects at runtime the suggested route is to do so in Awake/Start. There are many cases where doing it at runtime is required and theres nothing wrong with that but if you find yourself doing it ALOT then you will start to see some performance hits.
My personal opinion is setting your object references in the inspector is the safest as you know your reference is set because you manually dragged it in yourself. The issue you have with the methods they expose for you to find objects by name, tag, type, etc dont always work(especially if your gameobject is not active, a lot of them just wont find your object) and finding by name is always dangerous as all it takes is 1 person to change a name and it could mess everything up.
Generally speaking, FindObjectByType, Tag, etc can become very expensive if used often so like I said above you would want to minimize the amount of runtime finds you are doing with those(doing a couple GetComponents, etc every frame you won't see a big hit but if you do it on a larger scale you will see consequences.
The [SerializedField] attribute just tells the compiler to use Unitys serialization for that variable and expose it in the inspector. So, when you build, Unitys serializer just associated the reference you set in the inspector to that variable just like if you made the variable public instead of private with an attribute. Making it private obviously prevents you from accessing it outside that script but it will work just fine once you build.
TL;DR - I'd personally use the inspector as much as you can and expose your variables there and set your references instead of finding them at runtime. A lot of instances require finding objects at runtime and theres nothing wrong with using the methods Unity exposes but use them carefully and thoughtfully; dont find every object every frame its just a waste.