Teachers open the door but You must enter by yourself.

Open Media Lab.
オープンメディアラボ

玉転がし
Roll a Ball

【事前学習】前回学んだ機能を再確認しておきましょう。

Creating Collectibles

入力数値

オブジェクト名種類
PickUpCubePosition(0,0.5,0)
Rotation(45,45.45)
Scale(0.5,0.5,0.5)

回転するキューブのコードです。


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

public class Rotator : MonoBehaviour
{
	void Start(){
		tag="PickUp";//タグは事前に要生成
	}

	void Update(){
		transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
	}
}

prefab化したPickUpを使って、12個のPickUpをインスタンス化する際に、Positionは以下の表のように設定すると、きれいに円形に並びます。

オブジェクト名種類
PickUp (prefab後)CubePosition(0,0,5)
Position(2.5,0,4.25)
Position(4.25,0,2.5)
Position(5,0,0)
・・・

PickUpのコードによる生成

動画にはありませんが、回転するキューブPickUp12個をコードで生成する方法を試してみましょう。

  1. Hierarchy/Create/Create Emptyで空のGameObjectを生成して、例えば「Main」とします。
  2. Add Component/New Scriptで新しいC#のファイルを生成して例えば「Main」と命名して以下のコードを記述します。
  3. 最後にUnity側でMainを選択した状態でInspectorのScript部分に現れるPrefabのフォームにAssetsフォルダにあるPickUpのプレハブをドラッグ&ドロップします。

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

public class Main : MonoBehaviour
{
	public GameObject prefab;

	void Start(){
		for (int i = 0; i < 12; i++){
			var angle = i * Mathf.PI / 6f; //30°× i(単位はラジアン)
			var pickup=Instantiate(prefab);
			pickup.transform.position = new Vector3(
				Mathf.Cos(angle) * 5f,
				0.5f,
				Mathf.Sin(angle) * 5f
			);
		}
	}
}

【事後学習】本日学んだ機能を再確認しておきましょう。

This site is powered by Powered by MathJax