2017-05-30 87 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提供的所有不同的学习资源。你的问题是关于在所有不同的教程中肯定涵盖的相当基本的功能。