[unity] Awake 와 Start 의 차이
유니티는 사용자가 호출하지 않아도 호출되는 함수들이 있다. (유니티의 생명주기(LifeCycle)이라 부른다)
이 함수들은 사용자가 호출시기를 정할 수 없으므로 생명주기에 대해 이해하는 것이 유니티의 시작이다.
그 중
1 2 3 | void Awake() { } | cs |
항상 Start 전에 호출되며 프리팹이 인스턴스화 된 직후에 호출된다 (단, 게임오브젝트가 시작동안 비활성화인 경우 호출되지않는다)
1 2 3 4 | void Start() { } | cs |
스크립트 인스턴스가 활성화 된 경우 첫 번째 프레임 업데이트함수 호출 전 에 호출 된다.
다른 스크립트의 Awake가 실행 된 이후에 실행된다.
참조 Api : https://docs.unity3d.com/kr/530/Manual/ExecutionOrder.html
'Unity > 수업내용' 카테고리의 다른 글
조이스틱으로 이동하기 및 맵밖으로 이동시키지 않기 (0) | 2019.04.26 |
---|---|
버튼 누르면 공격 (반복) 및 데미지Text (0) | 2019.04.25 |
C#[delegate]대리자 (0) | 2019.04.16 |
Unity[유니티]MoveAttack(시간참조) (0) | 2019.04.12 |
Unity[유니티] 목표지점까지 이동 중 공격 (0) | 2019.04.11 |
unity 지정된 몬스터 공격 및 대상 삭제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class UIIngame : UIBase { public Material HitMaterial; private Material originMaterial; public void AddFx(string fxName, Vector3 fxPosition) { //fxName으로 fx 로드 var loadFx = Resources.Load<GameObject>(fxName); //로드된 fx로 프리팹 인스턴스화 var fxGo = GameObject.Instantiate<GameObject>(loadFx); //인스턴스화 된 프리팹을 fxpoint의 위치에 설정 fxGo.transform.position = fxPosition; var particle = fxGo.GetComponent<ParticleSystem>(); StartCoroutine(this.PlayFx(particle)); } private IEnumerator PlayFx(ParticleSystem fx) { fx.Play(); yield return new WaitForSeconds(fx.main.duration); Destroy(fx.gameObject); // fx 삭제 } public IEnumerator ChangeMaterial(Character init) { this.originMaterial = init.GetComponentInChildren<SkinnedMeshRenderer>().material; yield return new WaitForSeconds(0.1f); init.GetComponentInChildren<SkinnedMeshRenderer>().material = this.HitMaterial; yield return new WaitForSeconds(0.1f); init.GetComponentInChildren<SkinnedMeshRenderer>().material = this.originMaterial; } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | using System.Collections; using System.Collections.Generic; using UnityEngine; namespace yangjaejoon.scenes { public class InGame : MonoBehaviour { public UIIngame uiInGame; private Character hero; private Character stoneMonster; private Character bull; private StageBase currentStage; public void Awake() { AssetManager.GetInstance().LoadDatas("Prefabs"); DataManager.GetInstance().LoadCharacterData("Data/character"); DataManager.GetInstance().LoadCharacterAnimData("Data/character_anim"); DataManager.GetInstance().LoadStageData("Data/stage_data"); var stageDatas = DataManager.GetInstance().GetStageData(0); this.CreateStage<Stage_01>(stageDatas.id); //맵생성 this.hero = CreateCharacter(0); //영웅생성 this.stoneMonster = CreateCharacter(2); //스톤몬스터생성 this.bull = CreateCharacter(3); //불몬스터생성 this.hero.SetInitPosition(this.currentStage.position[0].position); this.stoneMonster.SetInitPosition(this.currentStage.position[1].position); this.bull.SetInitPosition(this.currentStage.position[2].position); } public void CreateWorld(int id) { var stageData = DataManager.GetInstance().dicStageData[id]; var stagePrefab = AssetManager.GetInstance().GetPrefab(stageData.prefab_name); var stageGo = Instantiate(stagePrefab); stageGo.transform.position = Vector3.zero; } public void Init(Camera uiCamera) { uiInGame.Init(uiCamera); this.uiInGame.FadeIn(); this.uiInGame.onFadeInCompleted = () => { Debug.Log("FadeIn완료"); this.hero.OnAttackRangeInMonster = () => { this.hero.Attack(stoneMonster); uiInGame.AddFx("Prefabs/UI/SwordHitRed", hero.transform.Find("DamagePoint").position); StartCoroutine( uiInGame.ChangeMaterial(stoneMonster)); this.hero.OnAttackStart = () => { if (this.stoneMonster.info.hp > 0) { this.hero.Attack(this.stoneMonster); uiInGame.AddFx("Prefabs/UI/SwordHitRed", hero.transform.Find("DamagePoint").position); StartCoroutine(uiInGame.ChangeMaterial(stoneMonster)); } else if (this.stoneMonster.info.hp <= 0) { this.stoneMonster.OnDieCompleted = () => { this.stoneMonster.Die(); this.stoneMonster = null; this.hero.Move(bull); this.hero.OnAttackRangeInMonster = () => { this.hero.Attack(bull); uiInGame.AddFx("Prefabs/UI/SwordHitRed", hero.transform.Find("DamagePoint").position); StartCoroutine(uiInGame.ChangeMaterial(bull)); this.hero.OnAttackStart = () => { if (this.bull.info.hp > 0) { this.hero.Attack(this.bull); uiInGame.AddFx("Prefabs/UI/SwordHitRed", hero.transform.Find("DamagePoint").position); StartCoroutine(uiInGame.ChangeMaterial(bull)); } else if (this.bull.info.hp <= 0) { this.bull.OnDieCompleted = () => { this.bull.Die(); this.bull = null; StartCoroutine(this.hero.PortalMove(this.currentStage.position[3].position)); }; } }; }; }; } }; }; this.hero.Move(stoneMonster); }; } public void CreateStage<T>(int id) where T : StageBase { var stageData = DataManager.GetInstance().GetStageData(id); var stagePrefab = AssetManager.GetInstance().dicLoadedAssets[stageData.prefab_name]; var stageGo = Instantiate(stagePrefab); stageGo.transform.position = Vector3.zero; this.currentStage = stageGo.GetComponent<T>(); } public Character CreateCharacter(int id) { var data = DataManager.GetInstance().GetCharacterData(id); var asset = AssetManager.GetInstance().dicLoadedAssets[data.prefab_name]; var characterGo = GameObject.Instantiate<GameObject>(asset); var modelPrefab = AssetManager.GetInstance().dicLoadedAssets[data.prefab_name]; var character = characterGo.AddComponent<Character>(); character.name = data.name; character.info = new yangjaejoon.CharacterInfo(id, data.hp, Vector3.zero); return character; } } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using CharacterInfo = yangjaejoon.CharacterInfo; public class Character : MonoBehaviour { public CharacterInfo info; private GameObject model; private Character target; private Animation anim; private Coroutine routine; public Action OnAttackStart; public Action OnAttackRangeInMonster; public Action OnDieCompleted; private int damage = 10; private int speed = 1; public void Awake() { this.anim = this.gameObject.GetComponent<Animation>(); } public virtual void Init(CharacterInfo info, GameObject model) { this.info = info; this.model = model; this.model.transform.SetParent(this.transform); this.model.transform.localPosition = Vector3.zero; } public virtual void SetInitPosition(Vector3 initPosition) { this.transform.position = initPosition; } public IEnumerator PortalMove(Vector3 position) { this.transform.LookAt(position); var data = DataManager.GetInstance(); var characterId = DataManager.GetInstance().GetCharacterData(this.info.Id); var characterData = data.dicCharacterData[characterId.id]; this.anim.Play(data.dicCharacterAnimData[characterId.anim_id].run_name); while (true) { var dir = (position - this.transform.position).normalized; var distance = Vector3.Distance(position, this.transform.position); this.transform.position += dir * this.speed * Time.deltaTime; if (distance <= 0.3f) { this.anim.Play(data.dicCharacterAnimData[characterId.anim_id].idle_name); Debug.Log("이동완료"); break; } yield return null; } } public void Move(Character target) { if (routine != null) { StopCoroutine(this.routine); } this.routine = StartCoroutine(this.MoveImpl(target)); } private IEnumerator MoveImpl(Character target) { this.transform.LookAt(target.transform); var data = DataManager.GetInstance(); var characterId = DataManager.GetInstance().GetCharacterData(this.info.Id); var characterData = data.dicCharacterData[characterId.id]; this.anim.Play(data.dicCharacterAnimData[characterId.anim_id].run_name); while (true) { var dir = (target.transform.position - this.transform.position).normalized; var distance = Vector3.Distance(target.transform.position, this.transform.position); this.transform.position += dir * this.speed * Time.deltaTime; if (characterData.attack_range > distance) { this.OnAttackRangeInMonster(); break; } if (distance <= 0.3f) { this.anim.Play(data.dicCharacterAnimData[characterId.anim_id].idle_name); Debug.Log("이동완료"); } yield return null; } } public void Attack(Character target) { if (routine != null) { StopCoroutine(this.routine); } this.routine = StartCoroutine(this.AttackImpl(target)); } private IEnumerator AttackImpl(Character target) { var data = DataManager.GetInstance().GetCharacterData(this.info.Id); var animName = DataManager.GetInstance().dicCharacterAnimData[data.anim_id]; var length = this.anim[animName.attack_name].length; var clip = this.anim[animName.attack_name].clip; var totalFrames = length * clip.frameRate; var attackFrame = 9; if (target.info.hp > 0) { this.anim.Play(animName.attack_name); var attackTime = attackFrame * length / totalFrames; yield return new WaitForSeconds(attackTime); target.transform.LookAt(this.transform.position); target.TakeDamage(this.damage); this.anim.Play(animName.idle_name); yield return new WaitForSeconds(length - attackTime); Debug.Log("공격완료"); } this.OnAttackStart(); } public void TakeDamage(int damage) { if (routine != null) { StopCoroutine(this.routine); } this.routine = StartCoroutine(this.TakeDamageImpl(damage)); } public virtual IEnumerator TakeDamageImpl(int damage) { var data = DataManager.GetInstance().GetCharacterData(this.info.Id); var animName = DataManager.GetInstance().dicCharacterAnimData[data.anim_id]; Debug.Log("공격"); this.info.hp -= damage; yield return null; if (this.info.hp <= 0) { this.info.hp = 0; this.anim.Play(animName.die_name); yield return new WaitForSeconds(anim[animName.die_name].length); this.OnDieCompleted(); Debug.LogFormat("{0}몬스터가 죽었습니다", data.name); } else { this.anim.Play(animName.hit_name); yield return new WaitForSeconds(anim[animName.hit_name].length); this.anim.Play(animName.idle_name); } } public void Die() { Debug.Log("몬스터삭제"); GameObject.Destroy(this.gameObject); } } | cs |
앞으로 해야 할 것 : 대상 공격 시 thumb 활성화 및 타격 받을 시 thumb의 hpbar 모션
대상이 타격받을 때 반격
영웅이 죽었을 때 재시작
이펙트 사용시 인스턴스화 시키고 삭제시키는 방법 말고 objectpool을 이용할 것
'Unity > 과제' 카테고리의 다른 글
타이틀씬까지 로드 (0) | 2019.04.18 |
---|---|
FadIn,FadOut 코드 (0) | 2019.04.17 |
[Unity]코루틴 사용하여 캐릭터 이동 및 공격모션 (0) | 2019.04.17 |
유니티 게임시작화면관리하기 (0) | 2019.04.16 |
유니티 캐릭터생성 및 위치지정 (0) | 2019.04.15 |
IEnumerator , yield 키워드
IEnumerator : 제너릭이 아닌 컬렉션을 단순반복할 수 있도록 지원하는 인터페이스
while 문과 foreach문을 사용하기 편하게 Coroutine으로 사용하는 인터페이스다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | public class App : MonoBehaviour { public Character hero; public Character monster; private Animation anim; private Character target; private float attackRange = 0.5f; private bool isStart; void Start() { StartCoroutine(this.hero.Move(new Vector3(5, 0, 5))); this.monster.Position(new Vector3(5, 0, 5)); StartCoroutine(this.monster.Attack(this.hero)); } private void Awake() { this.anim = this.gameObject.GetComponent<Animation>(); } public void Position(Vector3 position) { this.transform.position = position; } public IEnumerator Move(Vector3 tPos) { this.anim.Play("run@loop"); this.isStart = true; while(true) { if (this.isStart == true) { this.transform.LookAt(tPos); var dir = (tPos - this.transform.position).normalized; var speed = 1; this.transform.position += dir * speed * Time.deltaTime; var distance = Vector3.Distance(tPos, this.transform.position); if (attackRange > distance) { this.anim.Play("idle@loop"); this.isStart = false; if (distance <= 0.1f && this.isStart == true) { anim.Play("idle@loop"); Debug.Log("이동완료"); break; } } } yield return null; } } public IEnumerator Attack(Character target) { this.anim.Play("idle@loop"); this.target = target; while (true) { var distance = Vector3.Distance(this.transform.position, target.transform.position); if (attackRange > distance) { this.transform.LookAt(target.transform.position); anim.Play("attack_sword_01"); break; } yield return null; } } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public void Move(Vector3 tPos) { StartCoroutine(this.MoveImpl(tPos)); } private IEnumerator MoveImpl(Vector3 tPos) { this.anim.Play("run@loop"); this.isStart = true; while(true) { if (this.isStart == true) { this.transform.LookAt(tPos); var dir = (tPos - this.transform.position).normalized; var speed = 1; this.transform.position += dir * speed * Time.deltaTime; var distance = Vector3.Distance(tPos, this.transform.position); if (attackRange > distance) { this.anim.Play("idle@loop"); this.isStart = false; if (distance <= 0.1f && this.isStart == true) { anim.Play("idle@loop"); Debug.Log("이동완료"); break; } } } yield return null; } } | cs |
1 2 3 4 5 6 7 8 | public void Move(Vector3 tPos) { if (routine != null) { StopCoroutine(this.routine); } this.routine = StartCoroutine(this.MoveImpl(tPos)); } | cs |
참조 : https://docs.microsoft.com/ko-kr/dotnet/api/system.collections.ienumerator?view=netframework-4.7.2
참조 : https://www.slideshare.net/jungsoopark104/ienumerator
yield 키워드 : 호출자(Caller)에게 컬렉션 데이타를 하나씩 리턴할 때 사용
yield return : 각 요소를 따라 반환 , while문에서 쓴 이유 = 한 프레임마다 다시 돌리기 위함이다.
yield break : 리턴을 중지하고 Iteration 루프를 빠져나올 때 사용
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | //1번 public IEnumerator test() { //1번째 프레임 진입 yield return null; // 첫 프레임은 여기서 종료 //2번째 프레임 진입 Debug.Log("Hello world"); // 2번째 프레임에서 실행 // 함수내에 yield가 더이상 없기 때문에 종료. } //2번. public IEnumerator test2() { // 1번째 프레임 진입 Debug.Log("Hello world"); // 1번째 프레임에서 실행 yield return null; // 1번째 프레임에서 yield 시킴 // 2번째 프레임 진입 // 더이상 실행할 게 없으므로 종료. } | cs |
참조 : http://www.devkorea.co.kr/bbs/board.php?bo_table=m03_qna&wr_id=77246
캐릭터 이동공격 (오류 : takeDamage)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using CharacterInfo = yangjaejoon.CharacterInfo; public class Character : MonoBehaviour { public CharacterInfo info; private GameObject model; private Character target; private Animation anim; private Action OnCompletd; private Coroutine routine; private bool isMove = false; private bool isAttack = false; private bool isMoveCompleted = false; private int damage = 10; private int speed = 1; public void Awake() { this.anim = this.gameObject.GetComponent<Animation>(); } public virtual void Init(CharacterInfo info, GameObject model) { this.info = info; this.model = model; this.model.transform.SetParent(this.transform); this.model.transform.localPosition = Vector3.zero; } public virtual void SetInitPosition(Vector3 initPosition) { this.transform.position = initPosition; } public void Move(Character target) { if (routine != null) { StopCoroutine(this.routine); } this.routine = StartCoroutine(this.MoveImpl(target)); } private IEnumerator MoveImpl(Character target) { this.transform.LookAt(target.transform); var data = DataManager.GetInstance(); var characterId = DataManager.GetInstance().GetCharacterData(this.info.Id); var characterData = data.dicCharacterData[characterId.id]; while (true) { this.anim.Play(data.dicCharacterAnimData[characterId.anim_id].run_name); var dir = (target.transform.position - this.transform.position).normalized; var distance = Vector3.Distance(target.transform.position, this.transform.position); this.transform.position += dir * this.speed * Time.deltaTime; if (characterData.attack_range > distance) { this.Attack(target); break; } if (distance <= 0.3f) { this.anim.Play(data.dicCharacterAnimData[characterId.anim_id].idle_name); Debug.Log("이동완료"); } yield return null; } } public void Attack(Character target) { if (routine != null) { StopCoroutine(this.routine); } this.routine = StartCoroutine(this.AttackImpl(target)); } private IEnumerator AttackImpl(Character target) { var data = DataManager.GetInstance(); var characterId = DataManager.GetInstance().GetCharacterData(this.info.Id); var length = this.anim[data.dicCharacterAnimData[characterId.anim_id].attack_name].length; var clip = this.anim[data.dicCharacterAnimData[characterId.anim_id].attack_name].clip; var totalFrames = length * clip.frameRate; var attackFrame = 9; this.anim.Play(data.dicCharacterAnimData[characterId.anim_id].attack_name); var attackTime = attackFrame * length / totalFrames; yield return new WaitForSeconds(attackTime); StartCoroutine(target.TakeDamege(20)); yield return new WaitForSeconds(length - attackTime); Debug.Log("공격완료"); if (target.info.hp > 0) { this.Attack(target); } } public IEnumerator TakeDamege(int damage) { var data = DataManager.GetInstance(); var characterId = DataManager.GetInstance().GetCharacterData(this.info.Id); this.info.hp -= damage; if (this.info.hp <= 0) { this.info.hp = 0; this.anim.Play(data.dicCharacterAnimData[characterId.anim_id].idle_name); anim.Play("Anim_Death"); yield return new WaitForSeconds(anim["Anim_Death"].length); GameObject.Destroy(this.gameObject); } else { this.Attack(this.target); } } } | cs |
객체참조가 일어나지 않았다고 하는데.. 좀 더 알아봐야 할 것
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Logo : MonoBehaviour { public UILogo uiLogo; public void Init(Camera uiCamera) { this.uiLogo.Init(uiCamera); uiLogo.FadeIn(); this.uiLogo.onFadeInCompleted = () => { Debug.Log("Logo FadeIn완료"); StartCoroutine(this.uiLogo.WaitForSeconds(3)); uiLogo.onWaitForCecondsCompleted = () => { uiLogo.FadeOut(); }; }; this.uiLogo.onFadeOutCompleted = () => { Debug.Log("Logo FadOut완료"); var oper = SceneManager.LoadSceneAsync("Title"); oper.completed += (asyncOper) => { Debug.Log("Title로고씬 로드"); var title = GameObject.FindObjectOfType<Title>(); title.Init(uiCamera); }; }; } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class Title : MonoBehaviour { public UITitle uiTitle; private bool isRead; public void Awake() { this.uiTitle.btn.onClick.AddListener(() => { Debug.Log("버튼클릭함"); this.uiTitle.FadeOut(); //StartCoroutine(this.uiTitle.WaitForSeconds(3)); }); } public void Init(Camera uiCamera) { this.uiTitle.Init(uiCamera); this.uiTitle.FadeIn(); this.uiTitle.onFadeInCompleted = () => { Debug.Log("Title FadeIn 완료"); }; } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; namespace yangjaejoon.scenes { public class App : MonoBehaviour { public Camera uiCamera; private void Awake() { //인스턴스가 로딩될 때 Object.DontDestroyOnLoad(this); } // Start is called before the first frame update void Start() { var oper = SceneManager.LoadSceneAsync("Logo"); oper.completed += (asyncOper) => { var logo = GameObject.FindObjectOfType<Logo>(); logo.Init(this.uiCamera); }; } // Update is called once per frame void Update() { } } } | cs |
'Unity > 과제' 카테고리의 다른 글
unity 지정된 몬스터 공격 및 대상 삭제 (0) | 2019.04.24 |
---|---|
FadIn,FadOut 코드 (0) | 2019.04.17 |
[Unity]코루틴 사용하여 캐릭터 이동 및 공격모션 (0) | 2019.04.17 |
유니티 게임시작화면관리하기 (0) | 2019.04.16 |
유니티 캐릭터생성 및 위치지정 (0) | 2019.04.15 |