ふと気になり、
ChildクラスをMainCameraへアタッチし、Parentクラスが呼ばれるか実験
- 親クラス
using UnityEngine; using System.Collections; public class Parent : MonoBehaviour { void Start () { Debug.Log("ParentStart"); } void Update () { Debug.Log("ParentUpdate"); } }
- 子クラス
using UnityEngine; using System.Collections; public class Child : Parent { void Start () { Debug.Log("ChildStart"); } void Update () { Debug.Log("ChildUpdate"); } }
- 結果
ChildStart ChildUpdate ChildUpdate ChildUpdate ChildUpdate . . .
- 結論
親は無視!!!
子クラスから親を呼んだり、親クラスが自身のvirtualメソッドを呼んだら自動的に子クラスのoverrideメソッドを呼ぶか実験
アタッチしたのは子クラス
- 子クラス
using UnityEngine; using System.Collections; public class Child : Parent { void Update () { HelloParent(); } public override void Hoge() { Debug.Log("ChildHoge"); } }
- 親クラス
using UnityEngine; using System.Collections; public class Parent : MonoBehaviour { public virtual void Hoge() { Debug.Log("ParentHoge"); } public void HelloParent() { Debug.Log("Called From Child"); Hoge(); } }
- 結果はこうなった
Called From Child // 子クラスから呼ばれた親クラス ChildHoge // 子クラスのHogeメソッド Called From Child ChildHoge Called From Child ChildHoge . .
- 結論
virtualのメソッドは何を書いても意味が無い
親クラスが自身で持っているメソッドを呼ぼうとしたら、子クラスのoverrideのメソッドが呼ばれる