ブログ

リロード可能回数と残弾数を画面に表示する

(スクリプト)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ShotShell_X : MonoBehaviour
{
    public GameObject shellPrefab;
    public AudioClip shotSound;
    public AudioClip reloadSound;
    public int shellCount;
    public int reloadCount;
    public Text reloadlLabel;
    public GameObject[] shellIcons;

    private void Start()
    {
        reloadlLabel.text = "リロード可能回数:" + reloadCount;

        // shellアイコンの表示
        UpdateShellIcons();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0) && shellCount > 0)
        {
            shellCount -= 1;

            GameObject shell = Instantiate(shellPrefab, transform.position, Quaternion.identity);
            Rigidbody shellRb = shell.GetComponent<Rigidbody>();
            shellRb.AddForce(transform.forward * 500);
            AudioSource.PlayClipAtPoint(shotSound, Camera.main.transform.position);
            Destroy(shell, 5.0f);

            // shellアイコンの表示
            UpdateShellIcons();
        }

        if (Input.GetMouseButtonDown(1) && shellCount == 0)
        {
            if (reloadCount == 0)
            {
                return;
            }

            reloadCount -= 1;
            reloadlLabel.text = "リロード可能回数:" + reloadCount;

            shellCount = 3;
            AudioSource.PlayClipAtPoint(reloadSound, Camera.main.transform.position);

            // shellアイコンの表示
            UpdateShellIcons();
        }
    }

    void UpdateShellIcons()
    {
        for (int i = 0; i < shellIcons.Length; i++)
        {
            if (i < shellCount)
            {
                shellIcons[i].SetActive(true);
            }
            else
            {
                shellIcons[i].SetActive(false);
            }
        }
    }
}