如何像 Party Panic 那样创建盒子的生成?

How to create spawn of boxes like in Party Panic?

我是 Unity 的新手,我不明白如何制作一个脚本,让盒子像在这个游戏中一样生成。我试着自己做,但我的盒子只生成一次。

(在此视频中显示了应该发生的情况)https://youtu.be/rvyn5wVLYek?t=77

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

public class Spawner : MonoBehaviour {
 [SerializeField] private GameObject _box;
 [SerializeField] [Range(0, 5)] private int _minBoxes;
 [SerializeField] [Range(1, 25)] private int _maxBoxes;
 [SerializeField] private float _spawnHeight;
 void Start() {
    var size = GetComponent<MeshFilter>().sharedMesh.bounds.size.x * transform.localScale.x;
    var boxes = Random.Range(_minBoxes, _maxBoxes + 1);
    var step = size / boxes;

    for (int i = 1; i < boxes; i++) {
        Instantiate(_box, transform.position + new Vector3(step * i - size / 2f,  _spawnHeight), Quaternion.identity);
    }
 }
}

首先,欢迎来到Whosebug。

根据我在视频中看到的内容,您希望盒子以一定比例在特定 x 位置生成,这是我想出的代码。

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

public class BoxSpawn : MonoBehaviour
{
    public GameObject box;
    public float minXpos, maxXpos;
    public float timeBetweenBoxes;
    void Start()
    {
        //starts the loop for spawning boxes
        StartCoroutine(SpawnBox());
    }

    IEnumerator SpawnBox()
    {
        //get a random position on the x axis
        Vector3 boxPos = new Vector3(Random.Range(minXpos, maxXpos), 0, 0);

        //spawn the box
        Instantiate(box, boxPos, Quaternion.Euler(0, 0, 0));

        //let the code wait a certain time
        yield return new WaitForSeconds(timeBetweenBoxes);

        StartCoroutine(SpawnBox());
    }
}

将此脚本放在一个随机游戏对象上,并制作一个 Prefab 盒子游戏对象。将该预制件拖到 gameobject/script.

制作一个新脚本并将此代码放入该脚本:

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

public class Box : MonoBehaviour
{
    private float minSize = 0.5f; //minimum size
    private float maxSize = 2; //maximum size
    private float moveSpeed = 5;
    void Start()
    {
        //changes the size of the object to random values
        transform.localScale = new Vector3(Random.Range(minSize, maxSize), Random.Range(minSize, maxSize), Random.Range(minSize, maxSize));
    }

    void Update()
    {
        //moves the box in -z axis
        transform.Translate(new Vector3(0, 0, 1) * moveSpeed * Time.deltaTime);


        //destroys gameobject after a number of seconds (OPTIONAL BUT RECOMMENDED)
        //Destroy(gameObject, 10);
    }
}

将此脚本放在您创建的预制件上并将其拖到资产文件夹中以保存预制件,将预制件引用到 Spawner 游戏对象,它应该可以工作。

如果你想让盒子在物理上移动,给它添加一个刚体组件