Sprite spawn and despawn

I am trying to make a game create a prefab of a block that will change having it’s BoxCollider2D enabled and disabled everytime the player jumps.

While the mechanics of it is functioning, I want it to have a custom sprite that changes on each state.

Unfortunately I haven’t been able to get this to function at all with the sprite not animating.

Alternative methods I’ve come up with (that also don’t work) are having the Enabled sprite spawn and then de-spawn as the Disabled sprite spawns and the delete that to change back and forth. However in testing this, I haven’t been able to get the sprites to delete, they simply keep spawning over and over.

Is there anyway to implement this properly?
Ideally I would like to have the sprite animate between the two states, however in case I can’t get this to work for some reason, what would I have to do to get a sprite to spawn using the cordinates of a prefab (that is generated via script with variable positions) and then de-spawns the sprite to change it for another?

1 Answer

1

[RequireComponent (typeof(SpriteRenderer))]
[RequireComponent (typeof(Collider2D))]
public class myChangingBlock : MonoBehaviour
{
private Collider2D _coll;
private SpriteRenderer _sprite;

     public Sprite active_sprite;
     public Sprite inactive_sprite;

     void Start()
     {
           _coll = getComponent<Collider2D>();
           _sprite = getComponent<SpriteRenderer>();
      }

     public void switch(bool active) // your existent fuction
     {
           _coll.enabled = active;
          _sprite.sprite = (active ? active_sprite : inactive_sprite);
      }
}