UnityのGetComponentはAwake()で行うこと

いいたい事

public class Bar : MonoBehaviour {
  void Start() { // ダメ
    _view = GetComponent<BarView>();
  }

  private BarView _view;
}
public class Bar : MonoBehaviour {
  void Awake() { // 良い
    _view = GetComponent<BarView>();
  }

  private BarView _view;
}

なんでStart()じゃダメなの

バグの温床になるから。

どんなバグが起きるの

Null参照エラー、想定外の値が入っている等

具体例

public class Bar : MonoBehaviour {
  void Start() { // ダメ
    _view = GetComponent<BarView>();
  }

  public void OnNotify() {
    _view.UpdateView();
  }

  private BarView _view;
}
public class Main : MonoBehaviour {
  void Update() {
    if (_shouldInstantiate) {
      _bar = Instantiate(_bar) as Bar;
      _bar.OnNotify();

      _shouldInstantiate = false;
    }
  }

  [SerializeField] private Bar _bar;
  private bool _shouldInstantiate = true;
}

結果

f:id:SiunCyclone:20181020130814p:plain

上記エラーの原因がわからない場合は、Awake()とStart()の違いについて要復習

siuncyclone.hatenablog.com