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

如何引用实例化对象?实例化对象无法销毁问题排查

实例化对象无法通过鼠标命中销毁,NewPea为空

问题描述

我需要引用一个实例化的对象,让玩家用鼠标命中它时将其销毁。

更新说明:
编写了新代码但仍无法销毁对象,根据Debug.Log显示,NewPea为空,不指向任何对象。

相关代码

生成与销毁逻辑(PeaScript.cs)

transform.position = new Vector3(-3.89f, -0.76f, 0f);
Rot = transform.rotation;
Pos = transform.position;
NewPea = Instantiate(peaRB, Pos, Rot).gameObject;
Rigidbody2D NewPeaRB = NewPea.GetComponent<Rigidbody2D>();
NewPeaRB.AddForce(Vector2.right * 9, ForceMode2D.Impulse);
NewPeaRB.AddForce(Vector2.up * 9, ForceMode2D.Impulse);


}
}
public void PeaSelfDestroy()
{
    Debug.Log("death");
    Destroy(NewPea);
    Debug.Log(NewPea);
}

鼠标命中调用代码

_col.GetComponent<PeaScript>().PeaSelfDestroy();

问题分析与解决方案

核心问题

NewPea为空的原因大概率是作用域错误:如果NewPea是在生成方法内部声明的局部变量,那么PeaSelfDestroy方法无法访问到正确的实例引用,自然为空。

修复步骤

  1. 声明NewPea为类成员变量
    把NewPea的声明移到类的顶部,确保它在整个类的方法中都能访问:

    public class PeaScript : MonoBehaviour
    {
        private GameObject NewPea; // 类成员变量,而非局部变量
        // 你的其他变量(如peaRB)
    
        void SpawnPea() // 假设这是生成豌豆的方法
        {
            transform.position = new Vector3(-3.89f, -0.76f, 0f);
            var Rot = transform.rotation;
            var Pos = transform.position;
            NewPea = Instantiate(peaRB, Pos, Rot).gameObject;
            Rigidbody2D NewPeaRB = NewPea.GetComponent<Rigidbody2D>();
            NewPeaRB.AddForce(Vector2.right * 9, ForceMode2D.Impulse);
            NewPeaRB.AddForce(Vector2.up * 9, ForceMode2D.Impulse);
        }
    
        public void PeaSelfDestroy()
        {
            Debug.Log("death");
            if (NewPea != null)
            {
                Destroy(NewPea);
                Debug.Log("对象已标记销毁");
            }
            else
            {
                Debug.LogError("NewPea为空,无法执行销毁");
            }
        }
    }
    
  2. 验证鼠标命中的对象正确性
    确保_col是你实例化的豌豆对象:

    • 检查射线检测/鼠标点击逻辑,确认碰撞体_col确实属于生成的豌豆。
    • 可以在调用PeaSelfDestroy前打印_col.gameObject.name,验证是否是目标对象。
  3. 排查实例化阶段的赋值
    在Instantiate后立刻添加Debug.Log(NewPea),确认赋值时NewPea不为空,排除生成阶段的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 09:43:11