スペースシューター
Space Shooter
【事前学習】前回学んだ機能を再確認しておきましょう。
Scoring, Finishing and Building the Game
Counting points and displaying the score
操作手順
- Create/UI/Text でテキスト表示部分を生成し、Canvas/TextをCanvas/Score Textなどの名前にする。
- Canvas/Score Text を例えば左上ぞろえにして Position(10,-10,0) とするなどして画面左上に配置する。Color を視認性の良い白などに変更する。canvas の表示は Game ビューでしか確認できない。
- GameControllerにGameControllerのタグをつける。
- GameController.csに以下のように追記。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameController : MonoBehaviour { public GameObject hazard; public Vector3 spawnValues; public int hazardCount=10; public float spawnWait=0.5f; public float startWait=1.0f; public float waveWait=4.0f; public Text scoreText; private int score = 0; void Start(){ scoreText.text = "Score: 0"; StartCoroutine(SpawnWaves()); } IEnumerator SpawnWaves(){ yield return new WaitForSeconds(startWait); while (true) { for(int i=0;i<hazardCount; i++) { Vector3 spawnPosition = new Vector3( UnityEngine.Random.Range(-spawnValues.x,spawnValues.x), spawnValues.y, spawnValues.z ); Quaternion spawnRotation = Quaternion.identity; Instantiate(hazard, spawnPosition, spawnRotation); yield return new WaitForSeconds(spawnWait); } yield return new WaitForSeconds(waveWait); } } public void AddScore(int newScoreValue){ score += newScoreValue; scoreText.text = "Score: " + score; } }
- GameController の Inspector ウィンドウで、Score TextにCanvas/Score Text をドラッグアンドドロップ。
- DestroyByContact.cs に以下のように追記。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DestroyByContact : MonoBehaviour { public GameObject explosion; public GameObject playerExplosion; public int scoreValue=10; private GameController gameController; private void Start(){ GameObject gc = GameObject.FindWithTag("GameController"); if (gc != null){ gameController = gc.GetComponent<GameController>(); }else{ Debug.Log("Cannot find GameController Tag Object"); } } private void OnTriggerEnter(Collider other) { if (other.tag == "Boundary"){ return; } Instantiate(explosion, transform.position, transform.rotation); if (other.tag == "Player"){ Instantiate( playerExplosion, other.transform.position, other.transform.rotation ); } gameController.AddScore(scoreValue); Destroy(other.gameObject); Destroy(gameObject); } }
【事後学習】本日学んだ機能を再確認しておきましょう。