gpt4 book ai didi

c# - 按钮点击不能正常工作

转载 作者:行者123 更新时间:2023-11-30 12:57:28 28 4
gpt4 key购买 nike

我不知道我做错了什么这是一个二维项目,有两个对象。一个有一个 RigidBody2DBoxCollider2D 组件。第二个对象只有 BoxCollider2D。当按下按钮时底部有一个按钮 Object1 落在 Object2DestroyInstantiate Object1 再次。但是当 Object1 Instantiate 然后点击按钮时不起作用。错误是这样出现的:

Rigidbody2D 类型的对象已被销毁,但您仍在尝试访问它。您的脚本应该检查它是否为 null,或者您不应该销毁该对象。

对象 1:

enter image description here

对象 2:

enter image description here

按钮点击:

enter image description here

对象 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<Rigidbody2D> ().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。

清楚了吗?对不起我的英语。 :~

关于c# - 按钮点击不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34088939/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com