我不知道我做错了什么2D项目有两个对象.一个有RigidBody2D和BoxCollider2D组件.第二个对象只有BoxCollider2D.当按下按钮Object1落在Object2上并且再次销毁和实例化Object1时,底部有一个按钮.但是当Object1 Instantiate然后单击按钮不起作用.错误就像这样:
Rigidbody2D类型的对象已被破坏,但您仍在尝试访问它.您的脚本应该检查它是否为null或者您不应该销毁该对象.
对象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,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<Rigidbody2D> ().isKinematic = false; } }
1-将GameObject1Prefab(实时对象)拖到“我的”字段上的Object2脚本中.参考公共GameObject矿.
第一次点击你会销毁它,并创建一个新的,并在线上再次以编程方式引用新的:
mine = Instantiate (BallClone,Quaternion.identity) as GameObject;
在ClickButton对象上,在On Click()上拖动GameObject2而不是1.
这个清楚吗?对不起我的英文. :〜
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。