按钮单击无法正常工作

我不知道我做错了什么2D项目有两个对象。一个有RigidBody2DBoxCollider2D组件。 第二个对象只有BoxCollider2D 。 当按下按钮Object1落在Object2并且再次DestroyInstantiate Object1时,底部有一个按钮。 但是当Object1 Instantiate然后单击按钮不起作用。 错误就像这样:

The object of type Rigidbody2D has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

对象1:

在此处输入图像描述

对象2:

在此处输入图像描述

按钮单击:

在此处输入图像描述

对象1脚本:

 public class Object1 : MonoBehaviour { public static Object1 instance; [SerializeField] private Rigidbody2D body; [SerializeField] private bool hasdropped; [SerializeField] private bool click; [SerializeField] private float PointerPos; [SerializeField] private float BorderX; void Awake(){ if (instance == null) { instance = this; } //take width of screen Vector3 gameScreen = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height,0)); BorderX = gameScreen.x - 0.6f; body.isKinematic = true; click = true; hasdropped = true; } void FixedUpdate () { if (click) { Vector3 temp = transform.position; PointerPos = Camera.main.ScreenToWorldPoint(Input.mousePosition).x; temp.x = Mathf.Clamp(PointerPos,-BorderX,BorderX); body.position = temp; if(hasdropped){ return; } } } public void ButtonClick(){ body.isKinematic = false; } } 

对象2脚本:

 public class Object2 : MonoBehaviour { [SerializeField] private GameObject BallClone; void OnCollisionEnter2D(Collision2D target){ Destroy (target.gameObject); Instantiate (BallClone,new Vector3(0f,2f,59f),Quaternion.identity); } } 

问题是您在ClickButton On Click()上引用了Object1Prefab(活动对象,而不是预制件)。 (但参考预制件根本不起作用)

因为你破坏它,你错过了链接。 (检查一下:选择层次结构上的ClickButton对象,有脚本引用,对吗?单击游戏按钮一次。现在取消选择并再次选择层次结构上的ClickButton对象…它已消失。)

尝试创建一个监听器或将ButtonClick()方法放在object2中(你没有销毁):

 using UnityEngine; using System.Collections; public class Object2 : MonoBehaviour { [SerializeField] private GameObject BallClone; public GameObject mine; void OnCollisionEnter2D(Collision2D target){ Destroy (target.gameObject); mine = Instantiate (BallClone,new Vector3(0f,2f,59f),Quaternion.identity) as GameObject; } public void ButtonClick(){ //this is just an example. You might wanna to cache this info for better practice and not call GetComponent all the time mine.GetComponent ().isKinematic = false; } } 

1-将GameObject1Prefab(实时对象)拖到“我的”字段上的Object2脚本。 参考public GameObject mine

第一次点击你会摧毁它,并创建一个新的,然后在线上再次以编程方式引用新的:

 mine = Instantiate (BallClone,new Vector3(0f,2f,59f),Quaternion.identity) as GameObject; 

在ClickButton对象上,在On Click()上拖动GameObject2而不是1。

这个清楚吗? 对不起我的英文。 :〜