当然可以!以下是修改后的代码示例:

using UnityEngine;

public class CylinderGenerator : MonoBehaviour
{
    public GameObject prefab; // 预制体模型
    public float radius = 1f; // 圆柱体半径
    public float height = 1f; // 圆柱体高度

    [Range(1, 10)]
    public int cloneCount = 1; // 克隆数量

    void Start()
    {
        GenerateCylinders();
    }

    void OnValidate()
    {
        CalculateCloneCount();
    }

    void CalculateCloneCount()
    {
        if (prefab != null)
        {
            // 根据输入的高除以预制体的高来计算克隆数量
            cloneCount = Mathf.CeilToInt(height / prefab.GetComponent<Renderer>().bounds.size.y);
        }
    }

    void GenerateCylinders()
    {
        if (prefab != null)
        {
            for (int i = 0; i < cloneCount; i++)
            {
                // 在指定位置生成预制体,并设置旋转方向
                GameObject newObject = Instantiate(prefab, transform.position, Quaternion.identity);
                newObject.transform.SetParent(transform); // 设置生成的预制体为当前物体的子物体

                // 设置圆柱体的缩放和位置
                newObject.transform.localScale = new Vector3(radius * 2, height, radius * 2);
                newObject.transform.localPosition = new Vector3(0f, i * height, 0f);
            }
        }
    }
}

在上述代码中,我添加了GenerateCylinders函数,用于生成圆柱体预制体的克隆。在Start函数中调用GenerateCylinders函数,确保在游戏开始时生成圆柱体。

OnValidate函数中调用CalculateCloneCount函数,用于在编辑面板中修改参数时自动计算克隆数量。

GenerateCylinders函数中,使用Instantiate函数生成预制体的克隆,并设置其缩放和位置。transform.SetParent(transform)将生成的预制体设置为当前物体的子物体,以便更好地组织和管理。

现在,你可以在编辑面板中调整圆柱体的半径和高,并自动计算需要克隆的数量。每当你修改参数时,OnValidate函数会自动调用,并更新克隆数量。在游戏开始时,圆柱体预制体的克隆将被生成。


原文地址: https://www.cveoy.top/t/topic/uO0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录