unity3d - 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 initialization void start () { anim = getcomponent<animator> (); } // update 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 code. im trying when player presses button, swings sword spawning @ players location. works fine, when try remove sword error in unity:
invalidcastexception: cannot cast source type destination type. playerattack.attackcode () (at assets/scripts/player/playerattack.cs:33) playerattack.update () (at assets/scripts/player/playerattack.cs:22)
thanks advice.
by way, if knows of better way use weapons in unity2d open suggestions if way cumbersome way of doing things.
you must instantiate prefabs this.
prefabtypeobject obj = (typeofprefab)instantiate(prefab, position, rotation);
or
prefabtypeobject obj = instantiate(prefab, position, rotation) typeofprefab;
otherwise null object or invalidcastexception now.
your solution is`
clone = (gameobject)instantiate(swordobject_prefab.gameobject, player.position, quaternion.identity);
Comments
Post a Comment