【Unity】Instantiate関数について
忘れ防止のためちょこちょこ書きなぐっていきます。
今回もまた、おもちゃラボ様の記事を参考に進めていきたいと思います。
第2回へ突入です。
Instantiate関数とは、シューティングゲームで例えると、プレハブ化した物をプレイヤーが発射する時に使用する関数みたいなイメージです。
実際に記入したスクリプト(赤字)
〇プレイヤー
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RocketController : MonoBehaviour {
// Use this for initialization
public GameObject bulletPrefab;
// Update is called once per frame
void Update ()
{
if (Input.GetKey (KeyCode.LeftArrow)) {
transform.Translate (-0.1f, 0, 0);
}
if (Input.GetKey (KeyCode.RightArrow)) {
transform.Translate (0.1f, 0, 0);
}
if (Input.GetKeyDown (KeyCode.Space)) {
Instantiate (bulletPrefab, transform.position, transform.rotation);
}
}
}
〇弾
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletController : MonoBehaviour {
// Update is called once per frame
void Update () {
transform.Translate (0, 0.1f, 0);
if (transform.position.y > 5) {
Destroy (gameObject);
}
}
}
〇プレイヤー
public GameObject bulletPrefab;
略
if (Input.GetKeyDown (KeyCode.Space)) {
Instantiate (bulletPrefab, transform.position, transform.rotation);
→bulletPrefabを定義
スペースキーが押された瞬間、bulletPrefabをプレイヤーの場所から発射する。
Instantiate関数(ゲームオブジェクト,弾を生成する位置,弾の角度)を表す。
transform.rotationの所は、Quaternion.identityと記入しても両者がイコールのようなので、どちらでも良い。
最初のpublic GameObject bulletPrefab;を定義しておかないと弾が生成されない。弾の生成を急ぎ過ぎて、Instantiate関数に注意を向け過ぎないように注意する。
〇弾
transform.Translate (0, 0.1f, 0);
if (transform.position.y > 5) {
Destroy (gameObject);
→弾をy方向へ0.1fの距離進め、y方向へ進んだ距離が5に達したら弾を消去する。