LoginSignup
0
0

More than 3 years have passed since last update.

外部スクリプトを参照してスコアを加算する方法

Last updated at Posted at 2020-12-16

この記事でできること

  • 生成&消滅するオブジェクトに依存することなく、外部スクリプトの関数の使用によりスコアを加算することができる。

ダウンロード (1).gif

つくりかた(準備編)

サンプルSceneを準備する

プレファブで弾を発射する

  • 銃口(Muzzle)から弾(bullet)のクローンが発射される
Muzzle.cs
using UnityEngine;

public class Muzzle : MonoBehaviour
{
    public GameObject bullet;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Shot();
        }
    }

    void Shot()
    {
        GameObject obj;
        //====+====+====+====+====+====+====+====+====+====+====+====+====+====+
        //Instantiate関数の第二第三引数を設定することにより、通常の銃弾のような、
        //正しい向きが求められるbulletを生成することもできます。
        //====+====+====+====+====+====+====+====+====+====+====+====+====+====+
        obj = GameObject.Instantiate(bullet, transform.position, transform.rotation); 
        obj.GetComponent<Rigidbody>().AddForce(transform.forward * 1000);
    }
}

プレファブで敵を生成する

  • 適当なオブジェクトにアタッチすればOK。
EnemyGenerator.cs
using UnityEngine;

public class EnemyGenerator : MonoBehaviour
{
    public GameObject Enemy;
    private float x;
    private float y;
    private float z;

    void Start()
    {
        InvokeRepeating("Generate", 1, 1);
    }

    void Generate()
    {
        x = Random.Range(-5, 5);
        y = 1;
        z = Random.Range(-5, 5);
        Instantiate(Enemy, new Vector3(x, y, z), Quaternion.identity);
    }
}

つくりかた(本題編)

適当なオブジェクトに、スコア加算のスクリプトをアタッチする

  • スコア表示用のテキストラベルにアタッチするのが分かりやすいかもしれませんね。
ScoreCount.cs
using UnityEngine;
using UnityEngine.UI;

public class ScoreCount : MonoBehaviour
{
    private int intScore = 0;   //スコア加算用変数
    public Text ScoreText;      //画面に表示する文字をpublic変数とする

    public void ScoreAdd()
    {
        intScore++;
        ScoreText.text = intScore.ToString();
    }
}

たとえば弾に上記のスコア加算を呼び出すスクリプトを書くとこうなる

  • 下記だと弾に書いたけれども、敵に書いてもよい。
Bullet.cs
using UnityEngine;

public class Bullet : MonoBehaviour
{
    ScoreCount SCScriot;

    void Start()
    {
        //今回はCanvas内にscoreというテキストラベルのオブジェクトを作成して、
        //そこにスコア加算のスクリプトをアタッチしているので、
        //GameObject.Findで"Score"を探している。
        SCScriot = GameObject.Find("Score").GetComponent<ScoreCount>();
    }

    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.tag == "enemy")
        {
            SCScriot.ScoreAdd(); //←ここがスコア加算の呼び出し箇所。弾が敵に当たったら、スコア加算するよ、ということ。
            Destroy(gameObject);
        }
    }
}
  • スコア加算されたかな?
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0