2016-08-04 185 views
0

我的方法OnCollisionEnter有问题,我不知道它为什么不能正常工作。不知道如何在Unity3D中使用OnCollisionEnter

这里是我的代码:

void OnCollisionEnter(Collision col){ 

    if (col.gameObject.name == "Bullet" && !bulletEnter) 
    { 
     Debug.Log(enemyLives); 
     enemyLives = enemyLives - 1; 

     if (enemyLives == 0) 
     { 
      Destroy(gameObject); 
      //Modificamos el GameManager e incrementamos el dinero que poseemos tras la muerte de Enemy. 
      GameManager.Manager.currentGold(enemyGold); 
     } 

     bulletEnter = true; 


    } 
    else if (col.gameObject.name == "OtherBullet" && !bulletEnter) { 
     enemyLives = enemyLives - 2; 
     if (enemyLives == 0) 
     { 
      Destroy(this.gameObject); 
      GameManager.Manager.currentGold(enemyGold); 
     } 

     bulletEnter = true; 

    } 
} 

//Cuando sale la colision lo ponemos a false, esto lo realizamos para que unicamente exista un choque con los coliders. 
void OnCollisionExit(Collision col) 
{ 
    bulletEnter = false; 
} 

正如你可以看到有,当子弹到达敌人触发应被激活,但它不工作,我使用“的debug.log”,以检查是否它进入方法内部,但没有。

这里我还添加了我的检查员的照片。

enter image description here

+0

你在你的问题中发布的这个脚本的名字是什么,它附在哪里? – Programmer

+0

它命名为Enemy.cs,并附加到预制件称为“敌人”。 – fiticida

+0

好的。把'Debug.Log(“test”);'if语句之外,但在'OnCollisionEnter'里面,让我知道是否有日志。 – Programmer

回答

1

我创建了一个简单的场景,这和很快发现你的问题。取消选中触发器属性为敌方GameObject的Box Collider。现在应按预期调用OnCollisionEnter。的

。使用CompareTag不是按名称检查它:在你的代码

很少有其他的改进。只需将if (col.gameObject.name == "Bullet" && !bulletEnter)更改为if (col.transform.CompareTag("Bullet") && !bulletEnter)即可。

。还有,你有

void OnCollisionExit(Collision col) 
{ 
    bulletEnter = false; 
} 

这是不是一个好的逻辑,因为任何与敌人碰撞将被视为一个子弹。检查它是否为Bullet就像您在OnCollisionEnter功能中所做的那样,然后将bulletEnter设置为false。这可能会防止将来出现其他问题。

+0

或根据所需的行为将代码更改为“OnTriggerEnter”。 –

+0

谢谢你!它工作正常! – fiticida

+0

@GunnarB。是的,他可以做到这一点。这取决于他在做什么。 – Programmer