On RevisedBasicProject4
public class RevisedBasicProject4 : MonoBehaviour
{
public List<Transform> locationsOfObjects4 = new List<Transform>();
private void Start()
{
Objects4 = GetComponentsInChildren<Transform>();
foreach (var component in Objects4)
{
var item = (Transform) component;
locationsOfObjects4.Add(item);
}
Debug.Log(locationsOfObjects4.Count) //when i debug here,i can see results.
}
}
On RevisedBasicProject
public class RevisedBasicProject : MonoBehaviour
{
private void Start()
{
RevisedBasicProject4 revisedBasicProject4 = FindObjectOfType<RevisedBasicProject4>();
Debug.Log(revisedBasicProject4.locationsOfObjects4.Count);
//When i debug here i cannot see results
}
Is "FindObjectOfType" wrong way? why i cannot access it? Thank you for your time.
CodePudding user response:
Your issue is most probably execution order / race condition.
It is not guaranteed that RevisedBasicProject4.Start is executed before RevisedBasicProject.Start.
Convert the first Start to Awake to be sure it is definitely executed first.
My personal general thumb rule on this:
- Use
Awaketo initialize everything where you do not rely on others (e.g. forGetComponentcalls, initialize fields etc) - Use
Startwhere you do rely on others (like accessing fields of other components)
This solves most of order based issues.
Where this isn't enough you can still play with the Script Execution Order or use a more complex event system.
In general instead of FindObjectOfType if it is an option I would always prefer
[SerializeField] private RevisedBasicProject4 RevisedBasicProject4;
and drag in the according object into this slot in the Inspector within Unity.
