2013. 8. 19. 11:31
오브젝트의 성격에 따라 컴포넌트를 교체하고 싶을때 사용.
다음과 같이 상속을 구현.
부모 클래스(Parent.cs)
using UnityEngine; using System.Collections; public class Parent : MonoBehaviour { public virtual void PrintOut() { Debug.Log("Parent class"); } }
자식 1 (Child1.cs)
using UnityEngine; using System.Collections; public class Child1 : Parent { public override void PrintOut() { Debug.Log("Child1 class"); } }
자식 2 (Child2.cs)
using UnityEngine; using System.Collections; public class Child2 : Parent { public override void PrintOut() { Debug.Log("Child2 class"); } }
변환 관리자 (Manager.cs)
using UnityEngine; using System.Collections; public class Manager : MonoBehaviour { private GameObject cube; // Use this for initialization void Start () { cube = transform.FindChild("Cube").gameObject; } // Update is called once per frame void Update () { if (Input.anyKeyDown) { Debug.Log("anykey"); Component com = cube.GetComponent(typeof(Parent)) as Component; if (com.GetType() != typeof(Child2)) { Debug.Log("Destroy component"); Destroy(com); } cube.AddComponent(typeof(Child2)); Parent p = cube.GetComponent(typeof(Parent)) as Parent; p.PrintOut(); } } }
결과
하지만, 교체직후에는 Child1 이 출력되며, 한번의 호출을 더 하고서야 Child2가 출력된다.
즉, Destroy 나 AddComponent는 즉시(not immediately, deferred change) 이뤄지지 않는다.
또한, 에디트 모드(Edit mode)에서는 아예 실행조차 되지 않는다.
문제는 Destroy 부분으로, DestroyImmediate 로 교체해야 정상적으로 실행된다.
'Unity3D' 카테고리의 다른 글
[transform] Enable/Disable (0) | 2015.12.01 |
---|---|
[editor] Sprite Packer does not work... (0) | 2015.07.01 |
[Data] Serialization Inheritance Class with ScriptableObject (0) | 2013.12.10 |
[NGUI] UI와 일반 오브젝트의 터치 이벤트 처리. (1) | 2013.09.02 |