我正在制作一个移动项目,在立方体 RigidBody
的左右和上方有两个碰撞器,它们用鼠标控制。当我按下 Button
立方体 isKinematic = false
但问题是当它与对撞机发生碰撞时我想 Instantiate
一个新的立方体然后运行相同的过程.我写了代码,但它不工作。一个立方体下落,第二个立方体被实例化
,它不执行onClick
。
立方体脚本:
public class CubeScript : MonoBehaviour
{
private float pos;
private bool fall;
private bool exit;
[SerializeField]
private Rigidbody2D body;
void Awake ()
{
body.isKinematic = true;
fall = true;
exit = true;
}
void Update ()
{
if (fall) {
Vector3 temp = transform.position;
pos = Camera.main.ScreenToWorldPoint (Input.mousePosition).x;
temp.x = Mathf.Clamp (pos, -2.73f, 2.73f);
body.position = temp;
if (exit) {
return;
}
}
}
}
左对撞机:
public class LeftCollider : MonoBehaviour
{
public GameObject cube;
[SerializeField]
private BoxCollider2D collide;
[SerializeField]
private GameObject CubeClone;
private Button touchbutton;
void Awake ()
{
collide.isTrigger = true;
touchbutton = GameObject.FindGameObjectWithTag ("TouchButton").GetComponent<Button> ();
touchbutton.onClick.AddListener (() => CubeShoot ());
}
void OnTriggerEnter2D (Collider2D col)
{
Destroy (col.gameObject);
cube = Instantiate (CubeClone, new Vector3 (0f, 1.934f, 0f), Quaternion.identity) as GameObject;
}
public void CubeShoot ()
{
cube.GetComponent<Rigidbody2D> ().isKinematic = false;
}
}
右对撞机:
public class RightCollider : MonoBehaviour
{
public GameObject cube;
[SerializeField]
private BoxCollider2D collide;
[SerializeField]
private GameObject CubeClone;
private Button touchbutton;
void Awake ()
{
collide.isTrigger = true;
touchbutton = GameObject.FindGameObjectWithTag ("TouchButton").GetComponent<Button> ();
touchbutton.onClick.AddListener (() => CubeShoot ());
}
void OnTriggerEnter2D (Collider2D col)
{
Destroy (col.gameObject);
cube = Instantiate (CubeClone, new Vector3 (0f, 1.934f, 0f), Quaternion.identity);
}
public void CubeShoot ()
{
cube.GetComponent<Rigidbody2D> ().isKinematic = false;
}
}
最佳答案
这个问题有点相似,但现在你有 2 个对撞机:
Button click does not work correctly
根据实际编程,我让它工作的方式是:
对于 Collider(对于两者 - 注意第一行,我粘贴的是 LeftCollider,另一个应该是 RightCollider):
public class LeftCollider : MonoBehaviour {
//public GameObject cube;
[SerializeField]
private BoxCollider2D collide;
[SerializeField]
private GameObject CubeClone;
private Button touchbutton;
void Awake(){
collide.isTrigger = true;
touchbutton = GameObject.FindGameObjectWithTag ("TouchButton").GetComponent<Button> ();
touchbutton.onClick.AddListener (() => CubeShoot ());
}
void OnTriggerEnter2D(Collider2D col){
Destroy (col.gameObject);
Instantiate (CubeClone, new Vector3 (0f, 1.934f, 0f), Quaternion.identity);
}
public void CubeShoot ()
{
GameObject.FindGameObjectWithTag("cube").GetComponent<Rigidbody2D> ().isKinematic = false;
}
}
在预制件上放置标签:“立方体”(还要检查标签是否在事件立方体上,即一个层次结构)
应该这样做。
关于c# - 按钮 onClick 不会与对象发生碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34095856/