2017-05-30 92 views
1

我想讓我的玩家擊中一個物體,銷燬這個物體並觸發一個動畫,但是我嘗試的所有東西都會導致錯誤。我在c#中比較新,所以答案可能很明顯,但我需要幫助。我該如何設置它才能使對象消失並讓玩家播放動畫?這是我目前正在嘗試的腳本。碰撞觸發動畫

using System; 
using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
using UnityEngine.SceneManagement; 

public class succ : MonoBehaviour 
{ 
    public float speed = .15f; 
    public static float jumpSpeed = 170f; 
    void Start() 
    { 
     GetComponent<ConstantForce2D>().enabled = false; 
     GameObject.Find("goal"); 
    } 

    public bool animation_bool; 
    private object coll; 
    private object other; 

    void Update() 
    { 
     OnCollisionStay2D(Collision2D coll); 
     { 
      if (coll.gameObject.tag == "succ") ; 
      { 
       animation_bool = true; 
       GetComponent<Animator>().SetBool("succ", animation_bool); 
       GetComponent<ConstantForce2D>().enabled = true; 
       Destroy(other.object); 
      } 
     } 
    } 

    private void Destroy(object gameObject) 
    { 
     throw new NotImplementedException(); 
    } 

    private void OnCollisionStay2D(Collision2D collision2D, object coll) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+1

在'Update'函數內部看到'OnCollisionStay2D'回調函數後,我建議你先學習C#。那裏有很多在線教程。這將節省您的時間,同時,節省其他人的時間來閱讀您的問題。 – Programmer

回答

0

有幾件事我可以看到是錯的,但我會從回答你的問題開始。

我建議你改變你的MonoBehaviour方法OnCollisionStay2D到OnCollisionEnter2D。 OnCollisionStay2D是「發送到另一個對象上的碰撞器正在觸摸該對象的碰撞器的每個幀」。 「當傳入的對撞機與該物體的對撞機接觸時發送」OnCollisionEnter2D

我相信你正在尋找後者,因爲你只想在碰撞過程中觸發一次。您也正在銷燬另一個對象,即使您想這樣做,也無法再致電OnCollisionStay2D。

您還應該刪除Update方法。我真的不明白你現在想要達到的目標。所有OnCollision方法都會自動調用;你不必自己打電話給他們。

然後你可以使用覺醒與OnCollisionEnter2D方法如下

public class Succ : MonoBehaviour 
{ 
    private Animator animator; 

    private void Awake() 
    { 
     // You can already get a reference to the Animator on Awake 
     // This way you do not have to do it on every collision 
     animator = GetComponent<Animator>(); 
    } 

    // Use OnCollisionEnter2D instead since the code 
    // needs to be excecuted only once during the collision 
    private void OnCollisionEnter2D(Collision2D collision) 
    { 
     if (collision.gameObject.CompareTag("succ") 
     { 
      // Assuming that you only want to trigger an animation once 
      // to reflect attacking or colliding, you could use SetTrigger 
      // instead. Otherwise you need to use SetBool again to set it 
      // back to false. You should then change the Animator parameter 
      // accordingly, from a bool to a trigger. 
      animator.SetTrigger("succ"); 
      Destroy(collision.gameObject); 
     } 
    } 
} 
從這個

除此之外,我有幾件事我要評論:

  • 我不知道你試圖通過在Start上將ConstantForce2D組件設置爲false,然後在碰撞時將其設置爲true來實現。
  • 你似乎在開始使用GameObject.Find。 GameObject.Find是應該很少使用的東西。它可能非常昂貴,特別是如果你的場景中有很多GameObjects;這是因爲它只是通過Hiearchy,將參數字符串與GameObjects的名稱進行比較,直到它找到匹配項或用完GameObjects。
  • 此外,您在Start上使用GameObject.Find來查找GameObject,但不會將其存儲到任何地方,從而使整個查找過程完全沒有意義。

總的來說,我建議你看看Unity提供的所有不同的學習資源。你的問題是關於在所有不同的教程中肯定涵蓋的相當基本的功能。