- 最后登录
- 2014-10-23
- 注册时间
- 2011-7-19
- 阅读权限
- 90
- 积分
- 81303
![Rank: 8](static/image/common//star_level3.gif) ![Rank: 8](static/image/common//star_level3.gif)
- 纳金币
- -1
- 精华
- 11
|
Gettin’ Fancy
If you’ve read our article Understanding Loops with Arrays, you might have a notion of how to use Loops and Arrays to instantiate an armada of Prefabs into your scene. Here’s some sample code:
var myCube : GameObject;
function Start()
{
// Store a bunch of different positions in an Array:
var aPositions : Array = [new Vector3(0,0,0),
new Vector3(1,2,1),
new Vector3(2,1,1),
new Vector3(2,0,0),
new Vector3(0,3,0)];
var rot : Quaternion = Quaternion.identity;
// Loop as many times as there are elements in the aPositions Array:
for(i=0; i<aPositions.length; i++)
{
Instantiate(myCube, aPositions, rot); // Put a new cube on the screen using the i'th position
}
}
![]()
Here’s what it looks like.
One More for the Road
Just for kicks, here’s a script that’ll throw the cubes on the screen any old place, using Random.Range():
var myCube : GameObject; function Start() { // Let's store some minimum and maximum possible x,y and z values // to position our cubes: var minX : int = -5; var maxX : int = 5; var minY : int = -5; var maxY : int = 5; var minZ : int = -5; var maxZ : int = 5; // (you can fiddle with these numbers to change the range of possible spawn positions) var totalCubes : int = 50; // Change this to whatever number of cubes you'd like to have on-screen var rot : Quaternion = Quaternion.identity; for(i=0; i<totalCubes; i++) { // Use Random.Range to grab randomized x,y and z values within our min/max ranges: var randomX : int = Random.Range(minX, maxX); var randomY : int = Random.Range(minY, maxY); var randomZ : int = Random.Range(minZ, maxZ); var pos : Vector3 = new Vector3(randomX, randomY, randomZ); Instantiate(myCube, pos, rot); // Put a new cube on the screen using a randomized position } }
![]()
|
|