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

Unity中OnCollisionEnter()失效,如何修复随机物体碰撞销毁问题?

问题:使用Mathf.Round()处理生成位置后,Unity碰撞检测OnCollisionEnter()失效

我制作了一个随机生成器,需求是当生成的树木碰到自身或房屋时将其销毁,已为所有相关物体添加了碰撞体。该功能此前正常运行,但在使用Mathf.Round()处理生成位置后,OnCollisionEnter()不再生效。

碰撞检测脚本(TouchObject)

using UnityEngine;

public class TouchObject : MonoBehaviour
{
    private void OnCollisionEnter(Collision collision) 
    {
        if(collision.gameObject.name == "Structure") // 这里指树木
        {
            Destroy(gameObject);
        }

        if(collision.gameObject.name == "Floor") // 这里指房屋部件
        {
            Destroy(gameObject);
        }
    }
}

树木生成脚本(RandomGenerator)

using static System.Random;
using UnityEngine;

public class RandomGenerator : MonoBehaviour
{
    [Header("游戏对象")]
    public GameObject Tree;

    [Header("生成限制")]
    public int StuctLimit;

    [Header("随机坐标")]
    public int randomPosX;
    public int randomPosZ;

    private void Generating()
    {
        if(StuctLimit == 0)
        {
            System.Random randomPos = new System.Random();

            for (int i = 1; i <= 1500; i++)
            {
                randomPosX = randomPos.Next(10, 290);
                randomPosZ = randomPos.Next(10, 290);

                Instantiate(Tree, new Vector3(randomPosX, 0.0f, randomPosZ), Quaternion.identity);
            }
            StuctLimit++;
        }
    }

    private void Start()
    {
        Generating();
    }
}

房屋生成脚本(HouseGenerator)

using UnityEngine;

public class HouseGenerator : MonoBehaviour
{
    [Header("房屋对象")]
    public GameObject House;

    [Header("生成限制")]
    public int StuctLimit;

    [Header("随机坐标")]
    public int randomPosX;
    public int randomPosZ;

    private void Generating() 
    {
        if(StuctLimit == 0)
        {
            System.Random randomPos = new System.Random();

            for (int time = 0; time <= 20; time++)
            {
                randomPosX = randomPos.Next(10, 290);
                randomPosZ = randomPos.Next(10, 290);

                Instantiate(House, new Vector3(randomPosX, 0.5f, randomPosZ), Quaternion.identity);
            }
            StuctLimit++;
        }
    }

    private void Start()
    {
        Generating();
    }
}

注:我通过Instantiate(Object, new Vector3(positions), Quaternion.identity)创建物体,使用Mathf.Round(range)处理位置后出现问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:01:14