Unity - 2D Game [모각코]
갤러그다리
8.25 - 오늘은 텍스트 파일 txt를 이용해서 적 비행기를 커스텀 배치, 스테이지화 && 플레이어를 따라다는 보조무기를 만듦
- 텍스트 파일을 이용한 적 비행기 커스텀 배치
- 여태까지 랜덤한 타입의 적 비행체를 랜덤한 스폰 포인트에서 랜덤한 시간 배치로 스폰됬었다.
- 적 비행기를 소환하기 위해서 필요한 요소:
- 소환하는 시간 (Time)
- 적 비행기 종류 (Type)
- 소환할 위치 (Position)
- 위에 것들은 이미 다 만들어둠!
- 텍스트 데이터 - 윈도우 메모장(구조체 변수에 맞도록 값 입력, 구분자와 함께)
- 방법 : 메모장에 있는 내용을 리스트로 만든 뒤 Spwan Enemy 에서 하나하나 소환
- 파일 읽기를 위해 GameObject.cs에 Systme.IO 라는 헤더 파일을 사용해야한다.
- 작성한 텍스트 데이터는 Asset에 새 폴더(Resources)만들어 그곳에 넣어둔다.
- TextAsset: 텍스트 파일 에셋 클래스
- Resources.Load(): Resources 폴더내 파일 불러오기. - 텍스트 파일임을 검증하는 as 문법 사용
- StringReader: 파일내의 문자열 데이터 읽기 클래스
- ReadLine(): 텍스트 데이터를 한 줄씩 반환 (Auto 줄바꿈)
- 더 이상 랜덤 사용 X!
- Spwan.cs:
1 2 3 4 5 6 7 8 9 10 11 12
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spwan { public float delay; public string type; public int point; }
- 바뀐 코드(GameObject):
- 보조무기
- Follower.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
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Follower : MonoBehaviour { public float maxShotDelay; public float curShotDelay; public ObjectManager objectManager; public Vector3 followPos; public int followDelay; public Transform parent; public Queue<Vector3> parentPos; void Awake() { parentPos = new Queue<Vector3>(); } void Update() { Watch(); Follow(); Fire(); Reload(); } void Watch() { if(!parentPos.Contains(parent.position)) parentPos.Enqueue(parent.position); if(parentPos.Count > followDelay) followPos = parentPos.Dequeue(); else if (parentPos.Count < followDelay) followPos = parent.position; } void Follow() { transform.position = followPos; } void Fire() { if(!Input.GetButton("Fire1")) return; if(curShotDelay < maxShotDelay) return; GameObject bullet = objectManager.MakeObj("BulletFollower"); bullet.transform.position = transform.position; Rigidbody2D rigid = bullet.GetComponent<Rigidbody2D>(); rigid.AddForce(Vector2.up*10, ForceMode2D.Impulse); curShotDelay = 0; } void Reload() { curShotDelay += Time.deltaTime; } }