英文:
Unity how to randomize models?
问题
我正在开发一个Unity游戏。我有3个不同的模型,我想要做的是,在游戏进行几秒钟后,每次启动游戏时随机选择其中一个模型显示在屏幕上。我该如何做到这一点?请帮助。
英文:
I'm developing a Unity game. I have 3 different models, what I'm trying to do is, after few seconds of the game, I want one of these models appears on the screen randomly each time the game is started. How can I do that? please help.
答案1
得分: 1
Create a field to store the models
创建一个字段来存储模型
public List<GameObject> myModels;
然后在启动时随机选择一个
private void Start()
{
var randomizedIndex = Random.Range(0, myModels.Count);
var selectedModel = myModels[randomizedIndex];
// 实例化所选模型
}
英文:
Create a field to store the models
public List<GameObject> myModels;
then at start you randomize one
private void Start()
{
var randomizedIndex = Random.Range(0, myModels.Count);
var selectedModel = myModels[randomizedIndex];
// instantiate the selected model
}
答案2
得分: 1
using System.Collections.Generic;
using UnityEngine;
public class RandomObjectSpawner : MonoBehaviour
{
[SerializeField]
private float waitTime; // 等待实例化对象之前的时间
[SerializeField]
private List<GameObject> models; // 通过检视面板添加模型
private GameObject selectedModel;
private float timer;
void Start()
{
timer = 0f;
int randomizedIndex = Random.Range(0, models.Count);
selectedModel = models[randomizedIndex];
}
void Update()
{
timer += Time.deltaTime;
if (timer >= waitTime)
{
Instantiate(selectedModel); // 实例化我们的模型
}
}
}
注意
您需要通过检视面板分配您的模型和等待时间。
您需要将等待时间设置为大于0的值。
您可以修改对象生成的位置,默认情况下将生成在具有此脚本的对象的位置。
或者,您可以使用您选择的生成位置
Instantiate(selectedModel, spawnPosition, Quaternion.identity);
<details>
<summary>英文:</summary>
using System.Collections.Generic;
using UnityEngine;
public class RandomObjectSpawner : MonoBehaviour
{
[SerializeField]
private float waitTime; // The time You want to wait before Instantiating an object
[SerializeField]
private List<GameObject> models; // Your models Add them through the inspector
private GameObject selectedModel;
private float timer;
void Start()
{
timer = 0f;
int randomizedIndex = Random.Range(0, models.Count);
selectedModel = models[randomizedIndex];
}
void Update()
{
timer += Time.deltaTime;
if(timer >= waitTime)
{
Instantiate(selectedModel); // Instantiate our model
}
}
}
## Notes ##
You have to assign your models , WaitTime through the inspector .
You need to set the waitTime to a value bigger than 0 .
You can modify the Position an object spawns at , by default it will spawn in the position of the object with this script .
or You can use a spawnPosition of your choice
Instantiate(selectedModel,spawnPosition,Quaternion.identity);
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论