【问题标题】:Random spawning in an X and Y axis for several prefabs多个预制件在 X 和 Y 轴上随机生成
【发布时间】:2021-08-07 07:54:35
【问题描述】:

所以我创建了一个脚本,该脚本将根据按下到特定 x,y 位置的键来实例化不同的预制件。现在我想编辑它,而不是在特定点内生成,而是在 x1,x2 , y1,y2 区域内随机生成预制件。

这是我现在使用的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Instantiator : MonoBehaviour
{
    //Instantiator for Left
    public KeyCode keyToPress;
    public GameObject[] FI;
    public GameObject clone;

    // Update cause update is cooler
    void Update()
    {
        var transform.positionA = Vector2(Random.Range(-12, -10), Random.Range(-1, 1));
        var transform.positionD = Vector2(Random.Range(12, 10), Random.Range(-1, 1));
        var transform.positionS = Vector2(Random.Range(-1, 1), Random.Range(-6, -5));
        var transform.positionW = Vector2(Random.Range(-1, 1), Random.Range(6, 5));

        if (Input.GetKeyDown(KeyCode.A))
        {
            clone = Instantiate(FI[0], positionA, Quaternion.identity);
        }
        else if (Input.GetKeyDown(KeyCode.D))
        {
            clone = Instantiate(FI[1], positionD, Quaternion.identity);
        }
        else if (Input.GetKeyDown(KeyCode.S))
        {
            clone = Instantiate(FI[2], positionS, Quaternion.identity);
        }
        else if (Input.GetKeyDown(KeyCode.W))
        {
            clone = Instantiate(FI[3], positionW, Quaternion.identity);
        }

    }
}

但是,我收到语法错误 ["," expected 和 ";"预计]

【问题讨论】:

    标签: c# unity3d compiler-errors


    【解决方案1】:

    直接回答: 您需要使用new 关键字来创建新向量。 你不能使用 transform.position 作为变量..你必须使用Vector2 positionA = new Vector2(x, y) // or var positionA

    额外: 您可以使用Random.insideUnitCircle,它会在半径为 1 的圆内为您提供一个随机位置...如果您想增加半径,您可以将其乘以任何数字...例如Random.insideUnitCircle * 5 会给您一个随机位置在一个半径为 5 的圆中。您也可以通过向量添加或减去它,以将圆移动到不同的点。如果你想要一个随机的 3d 位置...你可以使用Random.insideUnitSphere。 例如:

    //Spawn an object between (startpos)Vector2(6f, -5f) to (endpos)Vector2(12f, -10f)
    Vector2 middle = new Vector2(startpos.x + endpos.x, startpos.y + endpos.y) / 2; // (6 + 12) / 2 = 18 / 2 = 9(which is the exact middle of 6 and 12)
    Instantiate(prefabname, middle + Random.insideUnitCircle * radius, Quaternion.identity);
    

    注意:如果你想让随机位置来自整个正方形,你将不得不使用传统的Random.Range函数,你也不需要每帧都创建位置......只需在实例化方法中创建它。

    【讨论】:

      猜你喜欢
      • 2017-04-09
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 2018-04-21
      相关资源
      最近更新 更多