I needed to find a better way to find my Game Objects without using GameObject.Find because I have this line more than 30 time is one script, so I created this line on my script:
public List<GameObject> gameObjectList = new List<GameObject>();
Then, I go in the inspector and add manually the gameobjects in the list.
and everything works fine. But I see nobody talking about that way on internet, so is there something wrong with that way?
CodePudding user response:
Assigning Object references using the Inspector is a great practice! It can make your components more flexible, because you can rewire the same code to work with different Objects.
Note that you can also expose private fields using the SerializeField attribute. Making fields private when you can is good practice, because limiting access to them can help reduce bugs.
Another things to note is that you can also edit Component type fields using the Inspector, so you don't need to do any GetComponent calls in your code. You rarely need to work with GameObjects directly; basically only when you want to destroy a GameObject or modify it's active state.
[SerializeField]
private Button[] buttons = new Button[0];
CodePudding user response:
You don't need to use GameObject.Find()
, you can just simply use Transform.GetComponent<>()
or other variations at Awake
and cache it, or you can assign it as you do at inspector.
I see you're using List for caching them. If you use the items with Index do not use list! It will make your code unreadable, Just store references separately.