【发布时间】:2019-01-13 19:51:24
【问题描述】:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spin : MonoBehaviour
{
public GameObject prefabToRotate;
[Range(1, 100)]
public int numberOfObjects = 5;
[Range(1, 500)]
public float[] speeds;
public bool randomNumbersOfObjects = false;
public bool randomSpeed = false;
private List<GameObject> instantiatedObjects = new List<GameObject>();
// Start is called before the first frame update
void Start()
{
speeds = new float[numberOfObjects];
if(randomNumbersOfObjects == true)
{
numberOfObjects = Random.Range(1, 100);
}
if(randomSpeed == true)
{
for(int i = 0; i < speeds.Length; i++)
{
speeds[i] = Random.Range(1, 500);
}
}
for(int i = 0; i < numberOfObjects; i++)
{
GameObject go = Instantiate(prefabToRotate);
instantiatedObjects.Add(go);
}
}
// Update is called once per frame
void Update()
{
for (int i = 0; i < numberOfObjects; i++)
{
instantiatedObjects[i].transform.Rotate(Vector3.down, speeds[i] * Time.deltaTime);
}
}
}
如何从 Range 滑块中获取随机数和随机速度? 1, 100 和 1, 500 ?我还希望能够在更新中更改滑块的这个值,它会在运行游戏时实时更新对象的数量和随机速度。
【问题讨论】:
-
要获取1到100之间的随机数,可以使用
Random rand = new Random();和int r = rand.Next(1, 100); -
@ES2018 这个是关于unitiy平台的,推荐使用unity提供的静态Random实例。
-
@ScottChamberlain,谢谢,是的,我知道静态总是更适合随机类型。我的建议只是给予和暗示。