簡體   English   中英

Unity2D C#-無法銷毀實例化的對象

[英]Unity2D C# - Can't destroy an Instantiated object

public class playerAttack : MonoBehaviour {

public bool attacking = false;

public Transform Player;
public Transform swordObject_prefab;
Animator anim;

GameObject clone = null;

// Use this for initialization
void Start () {
    anim = GetComponent<Animator> ();
}

// Update is called once per frame
void Update () {
    if (!attacking && !anim.GetBool ("isSwimming"))
            attackCode ();
    if (attacking)
        coolDown ();
}

void attackCode(){

    if (Input.GetButtonDown ("AttackA")) {
        Debug.Log ("ATTACK_A");
        anim.SetBool ("isAttackingA", true);
        attacking = true;
        clone = (GameObject)Instantiate(swordObject_prefab, Player.position, Quaternion.identity);
        Destroy(clone);

    }

    if (Input.GetButtonDown ("AttackB")) {
        anim.SetBool ("isAttackingB", true);
    }

}

void coolDown(){
    if (!anim.GetCurrentAnimatorStateInfo(0).IsName ("SwordSwing")) {
        attacking = false;
        anim.SetBool ("isAttackingA", false);

    }
}

這是我的代碼。 我試圖獲得此信息,以便當玩家按下按鈕時,他會在玩家所在的位置擺動一把產劍。 一切正常,但是當我嘗試卸下劍時,我在Unity中收到此錯誤:

InvalidCastException:無法從源類型轉換為目標類型。 playerAttack.attackCode()(在Assets / Scripts / Player / playerAttack.cs:33)playerAttack.Update()(在Assets / Scripts / Player / playerAttack.cs:22)

謝謝你的建議。

順便說一句,如果有人知道在Unity2D中使用武器的更好方法,那么如果這種方法做事麻煩,我將公開建議。

更改此行:

public Transform swordObject_prefab;

對此:

public GameObject swordObject_prefab;

但是我不確定立即銷毀剛剛創建的對象是為了...也許您想使用延遲嗎?

Destroy(clone, 2f); // Destroy clone 2 seconds from now

您必須像這樣實例化預制件。

PrefabTypeObject obj = (TypeOfPrefab)Instantiate(prefab, position, rotation);

要么

PrefabTypeObject obj = Instantiate(prefab, position, rotation) as TypeOfPrefab;

否則,您將像現在一樣獲得null對象或InvalidCastException。

您的解決方案是`

clone = (GameObject)Instantiate(swordObject_prefab.gameObject, Player.position, Quaternion.identity);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM