方法
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
public GameObject BlockPrefab;
void Start () {
Instantiate(this.BlockPrefab, new Vector3(0, 5, 0), Quaternion.identity);
}
}
- Instantiateで動的に生成できる。
- 引数1:コピー元
- 引数2:座標
- 引数3:回転
遊んでみた
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour
{
/// <summary>
/// ブロックプレハブ
/// </summary>
public GameObject BlockPrefab;
/// <summary>
/// 最下面中心ブロックの底面中心座標
/// </summary>
public Vector3 BasePos;
/// <summary>
/// 最大ブロック数
/// 1段3個*18段
/// </summary>
private const int MAX_BLOCKS = 3 * 18;
void Start()
{
//ブロック幅(長手方向)
float w = this.BlockPrefab.transform.localScale.x;
//ブロック幅(短手方向)
float d = this.BlockPrefab.transform.localScale.z;
//ブロック高さ
float h = this.BlockPrefab.transform.localScale.y;
for (int i = 0; i < MAX_BLOCKS; i++)
{
//何段目か
int step = Mathf.FloorToInt(i / 3) + 1;
//奇数段目
bool isOddStep = step % 2 == 1;
//短手方向オフセット
float depthOffset = ((i % 3) - 1) * d;
float x = isOddStep ? this.BasePos.x : this.BasePos.x + depthOffset;
float z = !isOddStep ? this.BasePos.z : this.BasePos.z + depthOffset;
float y = this.BasePos.y + (h / 2.0f) + (step - 1) * h;
Quaternion quat = isOddStep ? Quaternion.identity : Quaternion.Euler(0, 90, 0);
Instantiate(this.BlockPrefab, new Vector3(x, y, z), quat);
}
}
}
適当にブロックのプレハブ作って実行
![]() |
| 実行 |
| ジェンガっぽい何か |
おわり。
→Unity系記事まとめ
