■ はじめに
https://dk521123.hatenablog.com/entry/2018/10/14/113600
https://dk521123.hatenablog.com/entry/2020/02/24/185656
の続き。
■ サンプル
MainScene ... メイン用シーン GameOverScene ... ゲームオーバー用シーン
スクリプト例
BallScript : ボール用スクリプト
using UnityEngine; using UnityEngine.SceneManagement; public class BallScript : MonoBehaviour { private float speed; // Start is called before the first frame update void Start() { this.speed = Random.Range(5f, 15f); } // Update is called once per frame void Update() { transform.position += new Vector3(0f, 0f, -1 * this.speed * Time.deltaTime); if (transform.position.z < -13.0f) { Debug.Log("Game Over"); SceneManager.LoadScene("GameOverScene"); } } private void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Paddle")) { Destroy(gameObject); } } }
BallFactoryScript : 「Replay」ボタン用スクリプト
using UnityEngine; public class BallFactoryScript : MonoBehaviour { public GameObject ball; // Start is called before the first frame update void Start() { // ゲーム開始0秒後から1秒間隔で実行 InvokeRepeating("SpawnBall", 0f, 1f); } // 実行されるメソッド void SpawnBall() { // オブジェクトの生成 Instantiate( this.ball, new Vector3(Random.Range(-5f, 5f), transform.position.y, transform.position.z), transform.rotation); } // Update is called once per frame void Update() { } }
ReplayButtonScript : 「Replay」ボタン用スクリプト
using UnityEngine; using UnityEngine.SceneManagement; public class ButtonScript : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } // public にする必要がある public void ReplayGeme() { SceneManager.LoadScene("MainScene"); } }
関連記事
Unity ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2018/10/14/113600
Unity ~ 基本編 / スクリプト ~
https://dk521123.hatenablog.com/entry/2020/02/24/185656