Skip to content

Instantly share code, notes, and snippets.

@todorok1
Last active June 27, 2018 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todorok1/6b2efeab51c36a38d5f74c0c70474c5f to your computer and use it in GitHub Desktop.
Save todorok1/6b2efeab51c36a38d5f74c0c70474c5f to your computer and use it in GitHub Desktop.
立方体内に小さなオブジェクトをランダムにインスタンス化する
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomObjInstanciate : MonoBehaviour {
[SerializeField]
GameObject cubePrefab;
[SerializeField]
int batchNum = 5;
Vector3 cubeSize;
Vector3 offset;
const float min = -0.5f;
const float max = 0.5f;
void Start(){
cubeSize = gameObject.transform.localScale;
offset = gameObject.transform.localPosition;
}
void Update(){
InstantiateSmallCubeAtRandom();
}
void InstantiateSmallCubeAtRandom(){
// オブジェクトを立方体内のランダムな位置にインスタンス化する
for (int i = 1; i <= batchNum; i++){
float xPos = GetRandomRangeInCube() * cubeSize.x;
float yPos = GetRandomRangeInCube() * cubeSize.y;
float zPos = GetRandomRangeInCube() * cubeSize.z;
Vector3 position = new Vector3(xPos, yPos, zPos) + offset;
// Prefabをインスタンス化する
GameObject obj = Instantiate(cubePrefab, position, Quaternion.identity);
obj.transform.SetParent(gameObject.transform);
}
}
float GetRandomRangeInCube(){
float randomRange = Random.Range(min, max);
return randomRange;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment