You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity实现点击按钮从对象列表随机生成3个不同物品的方法

修改方案与完整代码

关键改动说明

  • 将单个生成对象替换为可在Inspector中编辑的对象列表,支持添加15个左右的候选对象
  • 实现随机选取3个不重复对象的逻辑
  • 给生成对象添加微小随机位置偏移,避免重叠
  • 增加安全校验,防止列表对象数量不足时出错

修改后的完整脚本

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

public class HerbSpawner : MonoBehaviour
{
    // 可生成对象列表,在Inspector中添加15个左右的候选对象
    public List<GameObject> spawnableObjects;
    public Transform groupTransform;
    // 生成位置的随机偏移范围,防止多个对象重叠
    public Vector2 spawnOffsetRange = new Vector2(0.2f, 0.2f);

    Vector2 spawnPos;

    void Start()
    {
        spawnPos = Camera.main.ViewportToWorldPoint(new Vector2(0.5f, 0.5f));
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit2D hit = Physics2D.GetRayIntersection(Camera.main.ScreenPointToRay(Input.mousePosition));

            if (hit.collider && hit.collider.CompareTag("Bush"))
            {
                SpawnRandomObjects();
            }
        }
    }

    void SpawnRandomObjects()
    {
        // 安全校验:如果列表为空或对象数量不足3个,直接返回
        if (spawnableObjects == null || spawnableObjects.Count < 3)
        {
            Debug.LogWarning("可生成对象列表为空或数量不足3个");
            return;
        }

        // 从列表中随机选出3个不重复的对象
        List<GameObject> selectedObjects = GetRandomUniqueObjects(3);

        // 基础生成位置
        Vector2 baseSpawnPos = Camera.main.ViewportToWorldPoint(new Vector2(0.5f, 0.7f));

        // 逐个生成选中的对象
        foreach (var obj in selectedObjects)
        {
            // 添加随机偏移,避免对象重叠
            Vector2 randomOffset = new Vector2(Random.Range(-spawnOffsetRange.x, spawnOffsetRange.x), 
                                              Random.Range(-spawnOffsetRange.y, spawnOffsetRange.y));
            Vector2 finalSpawnPos = baseSpawnPos + randomOffset;
            
            Instantiate(obj, finalSpawnPos, Quaternion.identity, groupTransform);
        }
    }

    // 从对象列表中随机获取指定数量的不重复对象
    List<GameObject> GetRandomUniqueObjects(int count)
    {
        List<GameObject> tempList = new List<GameObject>(spawnableObjects);
        List<GameObject> result = new List<GameObject>();

        for (int i = 0; i < count; i++)
        {
            int randomIndex = Random.Range(0, tempList.Count);
            result.Add(tempList[randomIndex]);
            tempList.RemoveAt(randomIndex);
        }

        return result;
    }
}

使用步骤

  1. 在Unity编辑器中选中挂载该脚本的对象
  2. 在Inspector面板的Spawnable Objects列表中点击+号,添加15个左右的候选生成对象
  3. (可选)调整Spawn Offset Range的值,控制生成对象的分散程度

内容的提问来源于stack exchange,提问作者kylorius beno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 03:57:21