如何使用 C# 将多个游戏对象的位置设置为不同的随机位置? (Unity5.5)
How do I set the positions of several game objects to DIFFERENT random positions with C#? (Unity5.5)
我有这段代码可以为几个游戏对象设置随机 x 和 z 坐标:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class SetPositions : MonoBehaviour
{
// Use this for initialization
void Start ()
{
System.Random rnd = new System.Random();
int a = rnd.Next (-9,9);
int b = rnd.Next(-9,9);
transform.position = new Vector3(a, transform.position.y, b);
}
}
当我将此脚本与多个游戏对象一起使用时,大多数游戏对象最终都位于完全相同的位置。我收集到这与使用的时间有关,但是如何确保所有对象都处于不同的位置?是否有在不同时间生成随机数的解决方法,或者是否应该移动代码 around/changed?
var rndPoint = (Random.insideUnitCircle * 9);
transform.position = new Vector3(rndPoint.x, transform.position.y, rndPoint.y);
var rndPoint = (Random.insideUnitSphere * 9);
rndPoint.y = transform.position.y;
transform.position = rndPoint;
感谢 Scott Chamberlain 的评论,我能够找到随机数的 Unity Documentation 并解决我的问题。 UnityEngine.Random 显然不使用时间,因此随机位置彼此不同。这是正确的脚本:
using UnityEngine;
using System.Collections;
public class SetPositions : MonoBehaviour
{
public GameObject PickUp;
void Start()
{
transform.position = new Vector3(Random.Range(-9.5f, 9.5f), 0.5f, Random.Range(-9.5f, 9.5f));
}
}
PickUp 是我用于所有拾取对象的预制件。
我有这段代码可以为几个游戏对象设置随机 x 和 z 坐标:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class SetPositions : MonoBehaviour
{
// Use this for initialization
void Start ()
{
System.Random rnd = new System.Random();
int a = rnd.Next (-9,9);
int b = rnd.Next(-9,9);
transform.position = new Vector3(a, transform.position.y, b);
}
}
当我将此脚本与多个游戏对象一起使用时,大多数游戏对象最终都位于完全相同的位置。我收集到这与使用的时间有关,但是如何确保所有对象都处于不同的位置?是否有在不同时间生成随机数的解决方法,或者是否应该移动代码 around/changed?
var rndPoint = (Random.insideUnitCircle * 9);
transform.position = new Vector3(rndPoint.x, transform.position.y, rndPoint.y);
var rndPoint = (Random.insideUnitSphere * 9);
rndPoint.y = transform.position.y;
transform.position = rndPoint;
感谢 Scott Chamberlain 的评论,我能够找到随机数的 Unity Documentation 并解决我的问题。 UnityEngine.Random 显然不使用时间,因此随机位置彼此不同。这是正确的脚本:
using UnityEngine;
using System.Collections;
public class SetPositions : MonoBehaviour
{
public GameObject PickUp;
void Start()
{
transform.position = new Vector3(Random.Range(-9.5f, 9.5f), 0.5f, Random.Range(-9.5f, 9.5f));
}
}
PickUp 是我用于所有拾取对象的预制件。