【问题标题】:How do I set the positions of several game objects to DIFFERENT random positions with C#? (Unity5.5)如何使用 C# 将多个游戏对象的位置设置为不同的随机位置? (Unity5.5)
【发布时间】:2017-07-16 11:14:05
【问题描述】:

我有这段代码可以为多个游戏对象设置随机 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);
    }
}

当我将此脚本用于多个游戏对象时,它们中的大部分最终都位于完全相同的位置。我已经收集到这与使用的时间有关,但是如何确保所有对象都处于不同的位置?是否有解决方法可以在不同时间生成随机数,或者是否应该移动/更改代码?

【问题讨论】:

标签: c# random unity5


【解决方案1】:

您可能需要Random.insideUnitCircle

var rndPoint = (Random.insideUnitCircle * 9);
transform.position = new Vector3(rndPoint.x, transform.position.y, rndPoint.y);

或Random.insideUnitSphere

var rndPoint = (Random.insideUnitSphere * 9);
rndPoint.y = transform.position.y;
transform.position = rndPoint;

【讨论】:

  • 我应该将代码放在我的脚本上下文中的什么位置?
【解决方案2】:

感谢 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 是我用于所有拾取对象的预制件。

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2022-07-14
    • 1970-01-01
    • 2018-02-04
    • 2018-12-11
    相关资源
    最近更新 更多