アイテムをランダムに出現させる


アイテムをランダムに発生させる
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyObject : MonoBehaviour
{
public GameObject effectPrefab;
public GameObject effectPrefab2;
public int objectHP;
// ★改良
// 配列の定義・・・>複数のデータを入れることのできる箱の作成
// public GameObject itemPrefab; この一行をコメントアウトする
public GameObject[] itemPrefabs;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Shell"))
{
objectHP -= 1;
if (objectHP > 0)
{
Destroy(other.gameObject);
GameObject effect = Instantiate(effectPrefab, transform.position, Quaternion.identity);
Destroy(effect, 2.0f);
}
else
{
Destroy(other.gameObject);
GameObject effect2 = Instantiate(effectPrefab2, transform.position, Quaternion.identity);
Destroy(effect2, 2.0f);
Destroy(this.gameObject);
// ★改良
// ランダム機能を使う
// 「Length」というプロパティを使うと、配列の要素数(「幾つの」データが入っているか)を測ることができます。
GameObject dropItem = itemPrefabs[Random.Range(0, itemPrefabs.Length)];
Vector3 pos = transform.position;
// ★改良
// itemPrefabをdropItemに変更する。
Instantiate(dropItem, new Vector3(pos.x, pos.y + 0.5f, pos.z), Quaternion.identity);
}
}
}
}



BattleTank(基礎/全31回)
他のコースを見る

アイテムをランダムに発生させる
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyObject : MonoBehaviour
{
public GameObject effectPrefab;
public GameObject effectPrefab2;
public int objectHP;
// ★改良
// 配列の定義・・・>複数のデータを入れることのできる箱の作成
// public GameObject itemPrefab; この一行をコメントアウトする
public GameObject[] itemPrefabs;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Shell"))
{
objectHP -= 1;
if (objectHP > 0)
{
Destroy(other.gameObject);
GameObject effect = Instantiate(effectPrefab, transform.position, Quaternion.identity);
Destroy(effect, 2.0f);
}
else
{
Destroy(other.gameObject);
GameObject effect2 = Instantiate(effectPrefab2, transform.position, Quaternion.identity);
Destroy(effect2, 2.0f);
Destroy(this.gameObject);
// ★改良
// ランダム機能を使う
// 「Length」というプロパティを使うと、配列の要素数(「幾つの」データが入っているか)を測ることができます。
GameObject dropItem = itemPrefabs[Random.Range(0, itemPrefabs.Length)];
Vector3 pos = transform.position;
// ★改良
// itemPrefabをdropItemに変更する。
Instantiate(dropItem, new Vector3(pos.x, pos.y + 0.5f, pos.z), Quaternion.identity);
}
}
}
}



アイテムをランダムに出現させる