简体   繁体   中英

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);

    }
}

Here's my code. Im trying to get it so when the player presses a button, he swings a sword spawning at the players location. that all works fine, but when i try to remove the sword I get this error in Unity:

InvalidCastException: Cannot cast from source type to destination type. playerAttack.attackCode () (at Assets/Scripts/Player/playerAttack.cs:33) playerAttack.Update () (at Assets/Scripts/Player/playerAttack.cs:22)

Thanks for the advice.

By the way, if anyone knows of a better way to use weapons in Unity2D I will be open to suggestions if this way is a cumbersome way of doing things.

Change this line:

public Transform swordObject_prefab;

To this:

public GameObject swordObject_prefab;

But I'm not sure what instantly destroying an object that has been just created is for... Maybe you want to use a delay?

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

You must instantiate prefabs like this.

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

or

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

otherwise you will get null object or InvalidCastException like now.

Your solution is`

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM