是否可以在 vector3 中包含一个变量?

Is it possible to include a variable inside of a vector3?

我想做一个有点像斜坡的游戏,每 3 秒就有一个新障碍。 我没有制作无限的生成点,而是想制作第一个并将 z 更改 20 像素。问题是我不知道如何让 Vector3 存储 2 个整数和一个变量。

我有点卡住了,所以我没有尝试任何东西,因为我不知道该尝试什么。

using System.Collections.Generic;
using UnityEngine;

public class levelgen : MonoBehaviour

{
    private int count = 9;
    public GameObject[] templates;


    // Update is called once per frame
    void Update()
    {
        public Vector3 spawn = new Vector3(-2, 0, count);
        int rand = Random.RandomRange(1, 5); //1-5 types of levels
        Instantiate(templates[rand], spawn1, Quaternion.identity);
        count = count + 20;

    }
}

我想将变量计数存储在 Vector3 spawn 中。

您不能将任何其他内容存储到 Vector3 或任何其他内置变量中*。你可以,而且你应该为你的变量制作自定义容器,比如 类 或 structs

public struct Custom
{
    int a;
    int b;
    string name;
    int count;
}

或类似

public struct Custom
{
    Vector3 vec;
    int count;
}

每次您想要更改新出生点的 z 轴时,您都需要将其重新分配给您的 Vector3 变量。您可以在 for 循环中执行此操作,如下所示。

zPosition 在这种情况下存储最新的 zPosition 值,因此您不需要将其存储在其他任何地方。如果你想在最初的 10 个障碍物之后产生更多障碍物,那么它将从它停止的 zPosition 处开始。

public class levelgen : MonoBehaviour
{
    public GameObject[] templates;
    public Vector3 spawn;
    int zPosition = 0;

    void Start()
    {
        GenerateObstacles(10);
    }

    void GenerateObstacles (int numObstacles)
    {
        for (int i = 0; i < numObstacles; i++)
        {
            spawn = new Vector3(-2, 0, zPosition);
            int rand = Random.Range(0, 6); //1-5 types of levels
            Instantiate(templates[rand], spawn, Quaternion.identity);
            zPosition += 20;
        }
    }
}

当然可以 可以 .. 但它不会再被称为 count 但例如z

public class levelgen : MonoBehaviour
{
    // You can not declare a public field within a method
    // so move it to class scope
    public Vector3 spawn = new Vector3(-2, 0, 9);
    public GameObject[] templates;

    // Update is called once per frame
    void Update()
    {
        // Here NOTE that for int parameters the second argument is "exclusiv"
        // so if you want correct indices you should always rather use
        int rand = Random.RandomRange(0, templates.Length);
        // I will just assume a typo and use spawn instead of spawn1
        Instantiate(templates[rand], spawn, Quaternion.identity);

        spawn.z += 20;

        // Or I would prefer since this works in general
        // Vector3.forward is a shorthand for writing new Vector3(0, 0, 1)
        // and this works in general
        spawn += Vector3.forward * 20;

        // you can e.g. NOT use
        //transform.position.z += 20
        // but only
        //transform.position += Vector3.forward * 20;
    }
}

注意 让这段代码 Instantiate 一个新对象 每帧 通常是一个非常糟糕的主意。如果你真的需要这么多对象,请查看 Object Pooling