实例化预制件
using UnityEngine;
public class InstantiationExample : MonoBehaviour
{
// 引用预制件。在 Inspector 中,将预制件拖动到该字段中。
public GameObject myPrefab;
// 该脚本将在游戏开始时简单地实例化预制件。
void Start()
{
// 实例化为位置 (0, 0, 0) 和零旋转。
Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity);
}
}
简单实例化;
using UnityEngine;
public class Wall : MonoBehaviour
{
public GameObject block;
public int width = 10;
public int height = 4;
void Start()
{
for (int y=0; y<height; ++y)
{
for (int x=0; x<width; ++x)
{
Instantiate(block, new Vector3(x,y,0), Quaternion.identity);
}
}
}
}
程序化生成,构建一堵墙;
长高分别为x,y.注意与下边z区分。
using UnityEngine;
public class CircleFormation : MonoBehaviour
{
// 以圆形形式实例化预制件
public GameObject prefab;
public int numberOfObjects = 20;
public float radius = 5f;
void Start()
{
for (int i = 0; i < numberOfObjects; i++)
{
float angle = i * Mathf.PI * 2 / numberOfObjects;
float x = Mathf.Cos(angle) * radius;
float z = Mathf.Sin(angle) * radius;
Vector3 pos = transform.position + new Vector3(x, 0, z);
float angleDegrees = -angle*Mathf.Rad2Deg;
Quaternion rot = Quaternion.Euler(0, angleDegrees, 0);
Instantiate(prefab, pos, rot);
}
}
}
构建一堵圆形,坐标是x和z.
更复杂的实例化操作,例如子弹撞击爆炸等,参考https://docs.unity.cn/cn/2020.3/Manual/InstantiatingPrefabs.html
更复杂的实例化操作,例如子弹撞击爆炸等,参考此处