gpt4 book ai didi

c# - 如何增加生成对象的 y(实例化)?

转载 作者:行者123 更新时间:2023-12-04 15:29:46 25 4
gpt4 key购买 nike

我怎样才能使预制件 2 在比预制件 1 更高的 y 上实例化。它们从同一位置随机生成。代码:

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
if (Time.time > nextSpawn)
{

what = Random.Range(1, 3);
Debug.Log(what);
switch (what)
{
case 1:
Instantiate(prefab1, transform.position, Quaternion.identity);
break;
case 2:
Instantiate(prefab2, transform.position.y, Quaternion.identity);
break;

}
nextSpawn = Time.time + SpawnRate;
}
}

抱歉,我知道解决方案可能很简单,但我就是找不到。

最佳答案

您的Instatiate 方法调用有问题。在您使用它的方式中,第二个参数需要是 Vector3 类型,而 transform.position.yfloat 类型。下面是一些示例代码,我相信您会发现它很有用。

float spawnRate = 5f;
float spawnTime;

//how high you would like your new object to spawn above transform.position
float yValueDifference = 5f;

void Update ()
{

if (Time.time - spawnTime > spawnRate)
{
//pick a random number from 0-1
int type = Random.Range(0, 2);

Vector3 position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
if (type == 1)
position.y += yValueDifference;

//if type is 0, use prefab1, if type is 1, use prefab2
GameObject prefab = type == 0 ? prefab1 : prefab2;
Instantiate(prefab, position, Quaternion.identity);

//reset the timer
spawnTime = Time.time;
}

}

关于c# - 如何增加生成对象的 y(实例化)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61464303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com