Unity教程-GameObject不会销毁

时间:2019-11-12 23:01:14

标签: c# unity3d destroy

我正在跟踪Unity中的Udemy 2D教程,以创建2D像素游戏。语言是C#。我只是复制代码,因为我不熟悉编码,但是我将代码复制到T上,而我的一个GameObjects遇到了问题。目的是每次启动剑游戏对象时都要销毁它,否则一堆副本就会出现在我的层次结构中。副本不会破坏自己。 如果我正确地读了这篇文章(可能不是因为我不是程序员,可能不是因为我),这源于另一段代码,该代码指出启动Sword时角色无法移动,但是此复选框不会切换回canMove =正确,将角色固定在适当的位置。当canMove = false时,Sword游戏对象不会销毁。用我的代码来解释可能会更容易。

这是我的Player canMove代码:

void Attack()
    {
        canMove = false;
        GameObject newSword = Instantiate(sword, transform.position, sword.transform.rotation);
        #region //SwordRotation
        int swordDir = anim.GetInteger("dir");
        if(swordDir == 0) 
    {
            newSword.transform.Rotate(0, 0, 0);
            newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.up * thrustPower);
    }
        else if (swordDir == 1)
    {
            newSword.transform.Rotate(0, 0, 180);
            newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.up * -thrustPower);
    }
        else if (swordDir == 2)
    {
            newSword.transform.Rotate(0, 0, 90);
            newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.right * -thrustPower);
    }
        else if (swordDir == 3)
    {
            newSword.transform.Rotate(0, 0, -90);
            newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.right * thrustPower);
    }
        #endregion


    }

    void Movement()
    {
        if (!canMove)
            return;
        if (Input.GetKey(KeyCode.W))
        { transform.Translate(0, speed * Time.deltaTime, 0); anim.SetInteger("dir", 0); anim.speed = 1; }
        else if (Input.GetKey(KeyCode.S))
        { transform.Translate(0, -speed * Time.deltaTime, 0); anim.SetInteger("dir", 1); anim.speed = 1; }
        else if (Input.GetKey(KeyCode.A))
        { transform.Translate(-speed * Time.deltaTime, 0, 0); anim.SetInteger("dir", 2); anim.speed = 1; }
        else if (Input.GetKey(KeyCode.D))
        { transform.Translate(speed * Time.deltaTime, 0, 0); anim.SetInteger("dir", 3); anim.speed = 1; }
        else
            anim.speed = 0;
    }

还有我的剑代码​​:

public class Sword : MonoBehaviour
{
    float timer = .15f;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        timer -= Time.deltaTime;
    if (timer <= 0)
    {
        GameObject.FindGameObjectWithTag("Player").GetComponent<Player>().canMove = true;
        Destroy(gameObject);
    }
    }
}

2 个答案:

答案 0 :(得分:0)

我在我的环境中检查了Sword代码,并且计时器似乎工作正常。 如果有的话,请检查Player对象是否已分配了标签“ Player”。如果找不到所需的对象,代码可能会在那里停止。

可以在检查器中的标签选项旁边的下拉菜单中找到分配标签的位置。

enter image description here

如果您已经完成此操作,请检查是否还有其他分配了“ Player”标签的对象。 FindGameObjectWithTag 将仅查找1个对象,该对象可能不是您要查找的对象。 如有疑问,请将这些行放在代码中的某个位置:

GameObject player = GameObject.FindGameObjectWithTag("Player");
Debug.Log(player.name);

这应该返回您要查找的对象的名称。 如果返回为null,则表示无法找到它。

答案 1 :(得分:0)

Destroy(gameObject);在您的Sword代码中。将其更改为Destroy(this.gameObject);

剑已经消失了。