So i’ve recently decided to get back into Makecode for a little bit after spending a couple of months learning C++ Gamedev, and one of the things I’ve been finding hard to adjust to is not being able the manage the lifetimes of my sprites. I can use the sprites.destroyAllSpritesOfKind function but I feel as though its limiting to need to make a SpriteKind that is forced to be destroyed. I’ve tried storing an array of sprites but that causes a null access exception. Is there a alternative solution?
@Alex can you share the code that’s giving you the exception?
let SpriteArr : Array<Sprite>
SpriteArr.push(sprites.create(SpriteTex.White))
Uncaught Dereferencing null/undefined value.
at (main.ts:1:1)
@Alex you need to assign that variable:
let spriteArray: Array<Sprite> = []
spriteArray.push(sprites.create(SpriteTex.White))
2 Likes
Hi, @Alex !
Also keep in mind that, depending on what specifically you’re trying to do, there may be built-in tools that can help you.
MakeCode is event-driven, so some aspects of sprite lifetime could be handled in, say, the sprite overlap event handlers.
There also is a sprite flag called auto-destroy. If a sprite with auto-destroy leaves the screen, then the sprite is automatically released without having to manage it explicitly.
let projectile: Sprite = sprites.create(img`.`, SpriteKind.Projectile)
projectile.setFlag(SpriteFlag.AutoDestroy, true)
projectile.setVelocity(25, 25)
Of course, there’s nothing wrong with managing sprite lifecycle yourself! Just know that there may be other tools available to help you.
1 Like