Unity2D C# - 无法销毁实例化对象

时间:2015-06-14 02:08:15

标签: c# unity3d

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中使用武器的更好方法,我会接受建议,如果这种做法是一种繁琐的做法。

2 个答案:

答案 0 :(得分:0)

更改此行:

for(int i=0;i<data.length;i++){
    var contentString = '<span>'+
    data[i].name +
    '</span>';    
}

对此:

public Transform swordObject_prefab;

但是我不确定是什么立即摧毁刚刚创建的对象是...也许你想要使用延迟?

public GameObject swordObject_prefab;

答案 1 :(得分:0)

你必须像这样实例化预制件。

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