I know that is much easy to use than referencing via script, but are there any cons where results more convenient to refence via script than drag & drop?
The references to my gameObjs via inspector don't give much confidence, can it reference lost for something like a modification in the code? I have to reference again everything I lost but if was a script reference where it find and pick I have doing fine I think.
What is best? inspector refences or script refences?, because where i read are ever a user saying that inspector refences are the best, the future and I don't understand what problems can give me and that have worried me.
Thank you for your response
CodePudding user response:
The con is that if you wanted to switch engines you would have to re-invent Unity's (de)Serialization system to migrate those refs. Other than that, referencing via drag & drop is the standard in Unity.
If someone has the necessary info regarding what objects can/cannot be referenced on what objects, they won't have to worry about losing existing references, and referencing data they could reference via the inspector from a script instead would be considered bad practice.
(practically the only rule is that scene objects can reference both prefabs and scene objects, but prefabs can only reference other prefabs, or specific parts of the prefab itself, like child objects)
An example of a bad practice would be using GetChild
to assign a reference to a public field:
public GameObject TextBox;
public GameObject ConfirmButton;
void Awake() {
TextBox = transform.GetChild(0);
ConfirmButton = transform.GetChild(1);
}
This is bad in many ways, including:
- This will break if you change the order of your objects in the hierarchy
- You don't really decouple from UnityEngine, since you're using its hierarchy system anyway
- You're assigning a value to a public field. This can confuse you and/or others working on the project into thinking that the public field's value would persist even after the object is instantiated. (protip: A good rule of thumb is to make all fields that are visible to the inspector immutable, as in not changeable throughout the object's lifetime).
PS: Mind that there are programming patterns that make use of passing around references via scripts to allow customizing the behaviour or looks of an object. Those are good!