MZ [Solved] Need help for making message bubble function

Hello, I've just started using RPG Maker MZ.I'm currently developing a fairly simple plugin to implement the necessary features for my game.

The plugin's content is as follows: creating message bubbles and playing animations
JavaScript:
/*:
 * @target MZ
 * @plugindesc Displays a message with background image and sound effect on the top right of the screen.
 * @help
 *
 * @param BackgroundImage
 * @text Background Image
 * @desc The background image filename (placed in img/pictures)
 * @default BackgroundImage
 * @type file
 * @dir img/pictures
 *
 * @param BackgroundImageBig
 * @text Background Image Big
 * @desc The background image filename (placed in img/pictures)
 * @default BackgroundImage
 * @type file
 * @dir img/pictures
 *
 * @param SoundEffect
 * @text Sound Effect
 * @desc The sound effect filename (placed in audio/se)
 * @default SoundEffect
 * @type file
 * @dir audio/se
 *
 * @param AnimationSpeed
 * @text Animation Speed
 * @desc The speed of the animation when messages move up/down (higher is faster)
 * @type number
 * @min 1
 * @default 10
 *
 * @param OffsetX
 * @text Offset X
 * @desc The horizontal offset from the right edge of the screen
 * @type number
 * @min 0
 * @default 10
 *
 * @param OffsetY
 * @text Offset Y
 * @desc The vertical offset from the top edge of the screen
 * @type number
 * @min 0
 * @default 10
 *
 * @command ShowPopupMessage
 * @text Show Popup Message
 * @desc Displays a message with background image and sound effect
 *
 * @arg message
 * @text Message
 * @desc The message to display
 * @type string
 * @default You got a potion!
 *
 * @arg duration
 * @text Duration
 * @desc The duration in seconds for the message to be displayed
 * @type number
 * @min 1
 * @default 15
 *
 * @command ShowPopupMessageBig
 * @text Show Popup Message Big
 * @desc Displays a message with background image and sound effect
 *
 * @arg message
 * @text Message
 * @desc The message to display
 * @type string
 * @default You got a potion!
 *
 * @arg duration
 * @text Duration
 * @desc The duration in seconds for the message to be displayed
 * @type number
 * @min 1
 * @default 15
 *
 * @command Init
 * @text Init
 * @desc Init
  *
 */

(() => {
    const pluginName = 'PM_Notification';

    const parameters = PluginManager.parameters(pluginName);
    const backgroundImage = parameters['BackgroundImage'];
    const backgroundImageBig = parameters['BackgroundImageBig'];
    const soundEffect = parameters['SoundEffect'];
    const offsetX = Number(parameters['OffsetX'] || 10);
    const offsetY = Number(parameters['OffsetY'] || 10);
    const animationSpeed = Number(parameters['AnimationSpeed'] || 10);

    let popupMessages = [];
    let zIndexCounter = 1000;

    PluginManager.registerCommand(pluginName, 'ShowPopupMessage', args => {
        const message = String(args.message);
        const duration = Number(args.duration);

        const scene = SceneManager._scene;
        const lastMessage = popupMessages.length > 0 ? popupMessages[popupMessages.length - 1] : null;

        let yPos = offsetY;
        if (lastMessage) {
            yPos = lastMessage.y + lastMessage.height + offsetY;
        }
       
        scene.showPopupMessage(backgroundImage, message, soundEffect, duration, offsetX, yPos);
    });
   
   
        PluginManager.registerCommand(pluginName, 'ShowPopupMessageBig', args => {
        const message = String(args.message);
        const duration = Number(args.duration);

        const scene = SceneManager._scene;
        const lastMessage = popupMessages.length > 0 ? popupMessages[popupMessages.length - 1] : null;

        let yPos = offsetY;
        if (lastMessage) {
            yPos = lastMessage.y + lastMessage.height + offsetY;
        }
       
        scene.showPopupMessage(backgroundImageBig, message, soundEffect, duration, offsetX, yPos);
    });
   
    PluginManager.registerCommand(pluginName, 'Init', args => {
        const scene = SceneManager._scene;

        // Show dummy popup message
        scene.showPopupMessage(backgroundImage, "Init", null, 5, 0, 0);
        scene.showPopupMessage(backgroundImageBig, "Init", null, 5, 0, 0);

        // Immediately remove the sprite if it exists
        if (scene.popupMessages) {
            if (scene.popupMessages.length > 0) {
                const sprite = scene.popupMessages[scene.popupMessages.length - 1];
                if (sprite) {
                    sprite.parent.removeChild(sprite);
                    scene.popupMessages.pop(); // Remove from array as well
                }
            }
        }
    });
   
    Scene_Base.prototype.showPopupMessage = function(imageName, message, soundName, duration, offsetX, offsetY) {
        let init = 0;
        if (message == "Init") {
            init = 1;
        }
       
        const bitmap = ImageManager.loadPicture(imageName);
        const sprite = new Sprite(bitmap);
        sprite.anchor.x = 0.5;
        sprite.anchor.y = 0.5;
       
        // Calculate initial position
        sprite.x = Graphics.width - (sprite.width/2) - offsetX;
        sprite.y = offsetY - (sprite.height/2);
       
        sprite.opacity = 0;
        sprite.z = zIndexCounter++;

        const textSprite = new Sprite(new Bitmap(bitmap.width, bitmap.height));
        textSprite.bitmap.drawText(message, 0, 0, bitmap.width, bitmap.height, 'center');
        textSprite.anchor.x = 0.5;
        textSprite.anchor.y = 0.5;
        sprite.addChild(textSprite);

        this.addChild(sprite);

        if (soundName != null){
            AudioManager.playSe({ name: soundName, volume: 90, pitch: 100, pan: 0 });
        }

        // Fade-in animation
        const fadeInDuration = 12; // 0.2 seconds at 60 fps
        const fadeOutDuration = 12; // 0.2 seconds at 60 fps
        const displayDuration = duration * 60; // Convert duration from seconds to frames
        let frame = 0;
       
        if (init == 1){
            frame = displayDuration-1;
        }
           
        const update = () => {
           
            sprite.x = Graphics.width - (sprite.width/2) - offsetX;
            textSprite.x = 0;
            textSprite.y = 0;
            const weight = Math.max((fadeInDuration * 20) - frame * 2, 0) * 0.00025;
            sprite.scale.x =  1 + Math.sin((frame / (fadeInDuration)) * 2) * weight;
            sprite.scale.y =  1 + Math.cos((frame / (fadeInDuration)) * 2) * weight;
                   
            if (sprite) {
                if (frame < fadeInDuration) {
                    sprite.opacity = (frame / fadeInDuration) * 255;
                } else if (frame >= displayDuration - fadeOutDuration) {
                    sprite.opacity = ((displayDuration - frame) / fadeOutDuration) * 255;
                } else {
                    sprite.opacity = 255;
                }
            }

            if (frame >= displayDuration) {
                if (sprite) {
                    sprite.parent.removeChild(sprite);
                    popupMessages = popupMessages.filter(item => item !== sprite);
                   
                }
            } else {
                frame++;
                requestAnimationFrame(update);
            }
            this.adjustPopupMessagesPosition();
           
        };
       
        update();
       
           
        popupMessages.push(sprite);
        this.adjustPopupMessagesPosition();

    };

    Scene_Base.prototype.adjustPopupMessagesPosition = function() {
        let currentY = offsetY;
        for (let i = 0; i < popupMessages.length; i++) {
            const sprite = popupMessages[i];
            if (sprite) {
                const targetY = sprite.height + i * (sprite.height + (sprite.height/4));
                sprite.y = sprite.y + Math.max(Math.abs(targetY - sprite.y) / 1000, 0) * (targetY - sprite.y);
               
            }
        }
    };

})();

However I got a major issue. There are no problems with creating message bubbles and playing animations, but the error occurs when the menu screen is opened while the animation is playing :"Uncaught TypeError: Cannot read property 'position' of null"

I believe this is likely because the Sprite created in the current Scene loses its target when the Scene transitions to the Menu.

To be honest, I'm a complete beginner in coding(I think you can easily see that in the codes), and I have no idea about the exact reason or even a possible solution for this error. I would greatly appreciate your help on this matter.

Also, if possible, explaining to me why this happen would really glad too.

Thank you!
Am I the only one who thinks it's strange someone who is self-professed beginner in RPG Maker and coding would immediately jump to writing a plugin?

Did you write that plugin or did ChatGPT write it? Because no, it doesn't look like something someone who is a beginner at coding would write.
Am I the only one who thinks it's strange someone who is self-professed beginner in RPG Maker and coding would immediately jump to writing a plugin?

Did you write that plugin or did ChatGPT write it? Because no, it doesn't look like something someone who is a beginner at coding would write.
My friend coded the base for me, and I messed with it like Frankenstein to get it to work as I intended. Plus I looked at other plugins that implemented similar functionality for structure.
I'm sure you can guess by full of disorderness in my codes.

Also I don't have any direct *coding career*, but I am a web developer, so hopefully this could be the answer for your curious!

And may I get an answer to my question if possible?
For now the only solution that comes to my mind is to keep track of sceneManager.changeScene and delete all the Message bubbles that were created immediately when the scene changes, and it looks kinda wonky.
Save yourself the headache of trying to reinvent the wheel and use Casper Gaming Toast Manager
Save yourself the headache of trying to reinvent the wheel and use Casper Gaming Toast Manager

Thanks for the great information. It seems beautiful plugin :LZSproud:
But what I'm looking for now is a clue to solve the problem so that I can create the plugin I want in the future (I know that it looks stupid, but still)
I also have a rather silly desire to have only the features I need, without the unnecessary options and customization that plugins have for offering universally to help a wider user.
Again, it's a lot easier and faster to use an existing plugin and just edit it for your use. Ive written a few plugins and I also have a massive file full of edits and patches I've made to other people's plugins to fit my use cases.
However I got a major issue. There are no problems with creating message bubbles and playing animations, but the error occurs when the menu screen is opened while the animation is playing :"Uncaught TypeError: Cannot read property 'position' of null"

I believe this is likely because the Sprite created in the current Scene loses its target when the Scene transitions to the Menu.
If the issue is the sprite losing its instance, you could correct it by checking if the sprite exists in the update cycle and end the update if it is missing.

Something like :


JavaScript:
const update = () => {
    if (!sprite || !sprite.parent) {
        return;
    }

    sprite.x = Graphics.width - (sprite.width/2) - offsetX;
    textSprite.x = 0;
    textSprite.y = 0;
    //rest of the code

This should handle the issue.
Hi!
I believe you should not use the requestAnimationFrame.
Instead, use the update method of the scene if you need something on the game loop.
By default, everything that is added to to the scene as a child, will be already updating together with the update method of the scene.

When you are going to the menu, I believe the requestAnimationFrame are still executing your update function, regardless it is on another scene.

So, try creating a class for your message box, and add it as a child to the scene.
I would not consider this to be a "simple" plugin.

Like Game_Message vs Window_Message, or Game_Temp vs Spriteset_Base & Sprite_Animation, you would generally want to create an abstract object, distinct from the PIXI display object, to handle the mechanics separately.

Also, as mentioned by others, your message bubbles would generally be implemented as a new class, probably inheriting from Window_Base, and would include an update method. The core scenes update their children each cycle. So this approach ensures that your additions update in sync with the existing game loop.
Again, it's a lot easier and faster to use an existing plugin and just edit it for your use. Ive written a few plugins and I also have a massive file full of edits and patches I've made to other people's plugins to fit my use cases.
Thanks for suggestion, and yes that would much easier.
But the main reason why I'm here is for learning, at least this time.


If the issue is the sprite losing its instance, you could correct it by checking if the sprite exists in the update cycle and end the update if it is missing.

Something like :


JavaScript:
const update = () => {
    if (!sprite || !sprite.parent) {
        return;
    }

    sprite.x = Graphics.width - (sprite.width/2) - offsetX;
    textSprite.x = 0;
    textSprite.y = 0;
    //rest of the code

This should handle the issue.
I thought same and tried this way and It worked most time, but sometimes (really don't know what point exactly triggering the error) the game kept trying referencing null.
So what I did is make a queue-clear function and check scene state every second, and clear all the objects when It changed :
Spoiler: Code
Code:
const _SceneManager_changeScene = SceneManager.changeScene;
SceneManager.changeScene = function() {
    const previousScene = this._scene;
    _SceneManager_changeScene.call(this);
    const currentScene = this._scene;
    if (previousScene !== currentScene && currentScene && currentScene.clearPopupMessages) {
        currentScene.clearPopupMessages();
    }
};

Scene_Base.prototype.clearPopupMessages = function() {
    while (popupMessages.length > 0) {
        const sprite = popupMessages.pop();
        if (sprite && sprite.parent) {
            sprite.parent.removeChild(sprite);
        }
    }
};
And yea it's dumb and dirty so I hoped there's another way to do this but couldn't find out in my tiny brain...


Hi!
I believe you should not use the requestAnimationFrame.
Instead, use the update method of the scene if you need something on the game loop.
By default, everything that is added to to the scene as a child, will be already updating together with the update method of the scene.

When you are going to the menu, I believe the requestAnimationFrame are still executing your update function, regardless it is on another scene.

So, try creating a class for your message box, and add it as a child to the scene.
Thanks for idea. I tried rewrote whole code with a class + removed requestAnimationFrame like below :
Spoiler: Code
Code:
(() => {
    const parameters = PluginManager.parameters('PSM_MessageBubble');
    const messageBubbleImage = String(parameters['MessageBubbleImage'] || '');
    const messageBubbleImageBig = String(parameters['MessageBubbleImageBig'] || '');
    const marginX = Number(parameters['MarginX'] || 10);
    const marginY = Number(parameters['MarginY'] || 10);
    const heightOffset = Number(parameters['HeightOffset'] || 10);
    const soundEffect = parameters['SoundEffect'];

    class MessageBubble extends Sprite {
        constructor(message, duration, img) {
            super();
            this._message = message;
            this._duration = duration;
            this._img = img;
            this._timer = 0;
            this.opacity = 0;
            this._initComponents();
        }

        _initComponents() {
            const imageFilename = this._img === 0 ? messageBubbleImage : messageBubbleImageBig;
            const image = ImageManager.loadPicture(imageFilename);
            image.addLoadListener(() => {
                this._body = new Sprite(image);
                this._body.anchor.set(0.5);
                
                this._text = new Sprite(new Bitmap(this._body.width, this._body.height));
                this._text.bitmap.drawText(this._message, 0, 0, this._body.width, this._body.height, 'center');
                this._text.anchor.set(0.5);
                
                this.addChild(this._body);
                this.addChild(this._text);
            });
        }

        update() {
            MessageQueue._updatePositions();
            super.update();
            let time_check = (this._duration - this._timer) / this._duration;
            let time_check_fadein = Math.max(((this._duration - (this._timer + this._duration / 1.5)) / this._duration), 0);
            this.scale.x = 1 + (Math.sin(time_check_fadein * 60) * time_check_fadein) * 0.1;
            this.scale.y = 1 + (Math.cos(time_check_fadein * 60) * time_check_fadein) * 0.1;
            if (time_check > 0) {
                this._timer++;
                if (this._timer < 15) {
                    this.opacity += 255 / 15;
                } else if (this._timer > this._duration - 15) {
                    this.opacity -= 255 / 15;
                }
            } else {
                this.parent.removeChild(this);
                MessageQueue.removeBubble(this);
            }
        }
    }

    class MessageQueue {
        static initialize() {
            this._queue = [];
        }

        static addBubble(message, duration, img) {
            const bubble = new MessageBubble(message, duration, img);
            SceneManager._scene.addChild(bubble);
            this._queue.push(bubble);
        }

        static removeBubble(bubble) {
            this._queue = this._queue.filter(b => b !== bubble);
        }

        static _updatePositions() { // This is where most of error came
            if (!this) return;
            let targetY = marginY + heightOffset * 2;
            this._queue.forEach(bubble => {
                if (!bubble.parent) return;
                if (!SceneManager._scene) return;
                bubble.x = Graphics.width - bubble._body.width / 2 - marginX;
                bubble.y = bubble.y * (1 - 0.1) + (targetY * 0.1);
                targetY += bubble._body.height + heightOffset;
            });
        }
    }

    MessageQueue.initialize();

    PluginManager.registerCommand('PSM_MessageBubble', 'QueueBubbleMessage', args => {
        const message = String(args.message);
        const duration = Number(args.duration);
        const img = message.length > 10 ? 1 : 0; // Determine which image to use based on message length
        MessageQueue.addBubble(message, duration, img);
        AudioManager.playSe({ name: soundEffect, volume: 25, pitch: 120, pan: 0 });
    });

    PluginManager.registerCommand('PSM_MessageBubble', 'InitBubbleMessage', args => {
        const message = "initialize";
        const duration = 0;
        const img = 0
        MessageQueue.addBubble(message, duration, img);
    });
    
})();
But the error still occured. For now as you can see I managed debuging by make some safety locks, It's clearly not a good solution. I think it's mostly because I still put them in sceneManager._scene, so I tried to find other way to put these in but seems that's over my level.
If I can find where should I put bubbles + queue in, It would be really nice since It's probably solve the problem bubbles get cleared whenever I opened the menu. maybe $gameScreen or something?...

May I can get some more advise for this maybe?


I would not consider this to be a "simple" plugin.

Like Game_Message vs Window_Message, or Game_Temp vs Spriteset_Base & Sprite_Animation, you would generally want to create an abstract object, distinct from the PIXI display object, to handle the mechanics separately.

Also, as mentioned by others, your message bubbles would generally be implemented as a new class, probably inheriting from Window_Base, and would include an update method. The core scenes update their children each cycle. So this approach ensures that your additions update in sync with the existing game loop.
I think inheriting Message class from Window_Base is really cool idea. but I couldn't managed solve the issue with this method too so I still needed put safety locks.
I should learn much more before make a plugin maybe.
Thanks for suggestion, and yes that would much easier.
But the main reason why I'm here is for learning, at least this time.



I thought same and tried this way and It worked most time, but sometimes (really don't know what point exactly triggering the error) the game kept trying referencing null.
So what I did is make a queue-clear function and check scene state every second, and clear all the objects when It changed :
Spoiler: Code
Code:
const _SceneManager_changeScene = SceneManager.changeScene;
SceneManager.changeScene = function() {
    const previousScene = this._scene;
    _SceneManager_changeScene.call(this);
    const currentScene = this._scene;
    if (previousScene !== currentScene && currentScene && currentScene.clearPopupMessages) {
        currentScene.clearPopupMessages();
    }
};

Scene_Base.prototype.clearPopupMessages = function() {
    while (popupMessages.length > 0) {
        const sprite = popupMessages.pop();
        if (sprite && sprite.parent) {
            sprite.parent.removeChild(sprite);
        }
    }
};
And yea it's dumb and dirty so I hoped there's another way to do this but couldn't find out in my tiny brain...



Thanks for idea. I tried rewrote whole code with a class + removed requestAnimationFrame like below :
Spoiler: Code
Code:
(() => {
    const parameters = PluginManager.parameters('PSM_MessageBubble');
    const messageBubbleImage = String(parameters['MessageBubbleImage'] || '');
    const messageBubbleImageBig = String(parameters['MessageBubbleImageBig'] || '');
    const marginX = Number(parameters['MarginX'] || 10);
    const marginY = Number(parameters['MarginY'] || 10);
    const heightOffset = Number(parameters['HeightOffset'] || 10);
    const soundEffect = parameters['SoundEffect'];

    class MessageBubble extends Sprite {
        constructor(message, duration, img) {
            super();
            this._message = message;
            this._duration = duration;
            this._img = img;
            this._timer = 0;
            this.opacity = 0;
            this._initComponents();
        }

        _initComponents() {
            const imageFilename = this._img === 0 ? messageBubbleImage : messageBubbleImageBig;
            const image = ImageManager.loadPicture(imageFilename);
            image.addLoadListener(() => {
                this._body = new Sprite(image);
                this._body.anchor.set(0.5);
               
                this._text = new Sprite(new Bitmap(this._body.width, this._body.height));
                this._text.bitmap.drawText(this._message, 0, 0, this._body.width, this._body.height, 'center');
                this._text.anchor.set(0.5);
               
                this.addChild(this._body);
                this.addChild(this._text);
            });
        }

        update() {
            MessageQueue._updatePositions();
            super.update();
            let time_check = (this._duration - this._timer) / this._duration;
            let time_check_fadein = Math.max(((this._duration - (this._timer + this._duration / 1.5)) / this._duration), 0);
            this.scale.x = 1 + (Math.sin(time_check_fadein * 60) * time_check_fadein) * 0.1;
            this.scale.y = 1 + (Math.cos(time_check_fadein * 60) * time_check_fadein) * 0.1;
            if (time_check > 0) {
                this._timer++;
                if (this._timer < 15) {
                    this.opacity += 255 / 15;
                } else if (this._timer > this._duration - 15) {
                    this.opacity -= 255 / 15;
                }
            } else {
                this.parent.removeChild(this);
                MessageQueue.removeBubble(this);
            }
        }
    }

    class MessageQueue {
        static initialize() {
            this._queue = [];
        }

        static addBubble(message, duration, img) {
            const bubble = new MessageBubble(message, duration, img);
            SceneManager._scene.addChild(bubble);
            this._queue.push(bubble);
        }

        static removeBubble(bubble) {
            this._queue = this._queue.filter(b => b !== bubble);
        }

        static _updatePositions() { // This is where most of error came
            if (!this) return;
            let targetY = marginY + heightOffset * 2;
            this._queue.forEach(bubble => {
                if (!bubble.parent) return;
                if (!SceneManager._scene) return;
                bubble.x = Graphics.width - bubble._body.width / 2 - marginX;
                bubble.y = bubble.y * (1 - 0.1) + (targetY * 0.1);
                targetY += bubble._body.height + heightOffset;
            });
        }
    }

    MessageQueue.initialize();

    PluginManager.registerCommand('PSM_MessageBubble', 'QueueBubbleMessage', args => {
        const message = String(args.message);
        const duration = Number(args.duration);
        const img = message.length > 10 ? 1 : 0; // Determine which image to use based on message length
        MessageQueue.addBubble(message, duration, img);
        AudioManager.playSe({ name: soundEffect, volume: 25, pitch: 120, pan: 0 });
    });

    PluginManager.registerCommand('PSM_MessageBubble', 'InitBubbleMessage', args => {
        const message = "initialize";
        const duration = 0;
        const img = 0
        MessageQueue.addBubble(message, duration, img);
    });
   
})();
But the error still occured. For now as you can see I managed debuging by make some safety locks, It's clearly not a good solution. I think it's mostly because I still put them in sceneManager._scene, so I tried to find other way to put these in but seems that's over my level.
If I can find where should I put bubbles + queue in, It would be really nice since It's probably solve the problem bubbles get cleared whenever I opened the menu. maybe $gameScreen or something?...

May I can get some more advise for this maybe?



I think inheriting Message class from Window_Base is really cool idea. but I couldn't managed solve the issue with this method too so I still needed put safety locks.
I should learn much more before make a plugin maybe.
It is still a little confuse for me. What you should really do is like Caethril said. Using a window for the message is the best, because you also be able to benefit from escape codes.
Take a look at the default code and see how Window Message and Window MapName are implemented for example.
But the main reason why I'm here is for learning, at least this time.
I know you have a notion and a plan in your head, and you're going to do what you want 😉

But my advice as a professional teacher is that's not an effective way to learn. The best way to learn something is to progress through the necessary knowledge and techniques in an orderly way, with lessons that incorporate what you learned previously to access something new.

Jumping into trying to do something fairly complex (even if, for some reason, you think it's simple) in a codebase you aren't familiar with using a programming langauge you're not proficient with is going to cause more frustration than it is going to help you learn.

There are many JavaScript tutorials, classes, and books available to help you in a good progressive way. What you're doing is kind of like jumping into a race car for the Indianapolis 500 to help you learn how to drive.

Just as a side note, your profile currently says your first language is English - if that's not the case, you should consider updating it (even if you leave it blank). That will help other people to answer you in the most effective way.

Good luck with your project, and keep asking for whatever you need.
I also just realised: you don't seem to be destroying the modified bitmaps (draw text) when their sprites are removed. I mentioned some relevant stuff in someone else's thread a few months ago, including suggestions about model/view components (i.e. separating mechanics & display):
However, I doubt that what I posted there will make much sense at your level of experience. 😴

If you want this kind of thing in your game, I recommend you follow Aqua's suggestion and use an existing plugin made by an expert. 👋

If you want to learn, I recommend starting with something much simpler, e.g. something that only modifies mechanics. Also, don't get someone else to do the majority of the legwork: the design phase is the most important part of software development, skipping it will teach you very little.
Thank you so much for your thoughtful advices!
I found the cause and solution.

the Bubble I made was a Sprite object, which referring PIXI, so no matter how much I tested if Bubble is null, it was a separate problem from ref error of position.
What PIXI refers for Position was not the object itself, but a Transform assigned to object.
So, I was able to solve it in the following way.

this._queue.forEach(bubble => { if (bubble.transform != null) { //position codes } };



I also just realised: you don't seem to be destroying the modified bitmaps (draw text) when their sprites are removed. I mentioned some relevant stuff in someone else's thread a few months ago, including suggestions about model/view components (i.e. separating mechanics & display):
However, I doubt that what I posted there will make much sense at your level of experience. 😴

If you want this kind of thing in your game, I recommend you follow Aqua's suggestion and use an existing plugin made by an expert. 👋

If you want to learn, I recommend starting with something much simpler, e.g. something that only modifies mechanics. Also, don't get someone else to do the majority of the legwork: the design phase is the most important part of software development, skipping it will teach you very little.
Yea, I thought it was a simple script at first, but the more I worked on it the more I realized it wasn't.
As other people's comments above say, I should have gotten a little more digging with the basic js files in RMMZ before starting this.

And there seems to be no performance degradation caused by not destroying bitmap at this time for now.
I tested with generating 10 bubbles per sec / 20min, but it soon returned to normal even if the memory went up temporarily, and FPS also had no issue.
Can the performance issue with unmanaged Bitmap be fatal?



I know you have a notion and a plan in your head, and you're going to do what you want 😉

But my advice as a professional teacher is that's not an effective way to learn. The best way to learn something is to progress through the necessary knowledge and techniques in an orderly way, with lessons that incorporate what you learned previously to access something new.

Jumping into trying to do something fairly complex (even if, for some reason, you think it's simple) in a codebase you aren't familiar with using a programming langauge you're not proficient with is going to cause more frustration than it is going to help you learn.

There are many JavaScript tutorials, classes, and books available to help you in a good progressive way. What you're doing is kind of like jumping into a race car for the Indianapolis 500 to help you learn how to drive.

Just as a side note, your profile currently says your first language is English - if that's not the case, you should consider updating it (even if you leave it blank). That will help other people to answer you in the most effective way.

Good luck with your project, and keep asking for whatever you need.
True. I'll study RMMZ core codes much more before start make one next time.
Setting up native language to eng was a mistake T.T, sorry if you felt weird.




Thank you all!
And there seems to be no performance degradation caused by not destroying bitmap at this time for now.
I tested with generating 10 bubbles per sec / 20min, but it soon returned to normal even if the memory went up temporarily, and FPS also had no issue.
FPS is capped to the ticker rate by default: you should at least be looking at frame duration (F2 twice). But afaik a memory leak will typically saturate RAM, with minimal impact (until that point) on other resources. For properly investigating stuff at this level, I'd recommend using the Performance tab of the dev tools window (F8 or F12) rather than relying on tools like the Task Manager. 👋

Also, your test might not even cause a memory leak, depending on how you wrote it. E.g.
  • PIXI, or the browser/compiler, may skip certain aspects of your test.
  • If each test replaced the previous one with identical image data, maybe only 1 texture was retained.
The main reason you should call destroy is because PIXI's texture batching blocks standard garbage collection. I'm no expert on PIXI...it's possible it implements GC-like checks to compensate for that. Given destroy exists, though, I figure it should be used! 😊

Setting up native language to eng was a mistake
In case it helps, account details (including First Language) can be edited here~
I thought the problem was fixed, but I often got a reference error afterwards.
Trigger was quite random, but most of them seemed to be caused by the order of update by fine lag and game speed.

I wanted to expand this structure and implement a lot of things in future, so I kept track what is wrong for a while, In the end, I was able to find the answer by looking back on all of your advice and reviewing my codes.

So the key problem was that the position of Bubble Sprite, an object made of Pixi Sprite, was remotely managed by BubbleManager that the custom class I made.
The update cycle/delete/reference timing of Bubble Sprite was different from that of the Bubble Manager Class, so Bubble Manager kept tried to refer to Bubble when the Pixi Transform of the Bubble was already deleted but not the Bubble itselt yet.
Which resulting in an "error that Bubble exists but cannot refer to the position value".

The solution was that BubbleManager Class only included the Add and Remove of BubbleSprite, Managing queue, and the function that pass the index of each BubbleSprite objects in the queue.
Any reference to the Sprite element, such as the position of the Bubble Sprite, was made to be resolved inside the Bubble Sprite object.

Theoretically by not making remote references, the error can no longer occur anymore, And the error has actually been resolved!

Thank you so much for your help.
FPS is capped to the ticker rate by default: you should at least be looking at frame duration (F2 twice). But afaik a memory leak will typically saturate RAM, with minimal impact (until that point) on other resources. For properly investigating stuff at this level, I'd recommend using the Performance tab of the dev tools window (F8 or F12) rather than relying on tools like the Task Manager. 👋

Also, your test might not even cause a memory leak, depending on how you wrote it. E.g.
  • PIXI, or the browser/compiler, may skip certain aspects of your test.
  • If each test replaced the previous one with identical image data, maybe only 1 texture was retained.
The main reason you should call destroy is because PIXI's texture batching blocks standard garbage collection. I'm no expert on PIXI...it's possible it implements GC-like checks to compensate for that. Given destroy exists, though, I figure it should be used! 😊


In case it helps, account details (including First Language) can be edited here~

Thank you for your advice.

I'm not against your opinion, but it seems that GC in rmmz and js VN is already working brilliantly just by destroying Sprite made of Bitmap.

I wrote a code for test that repeats a series of routines that generate random bitmap, generate Sprite with that bitmap, render it to Scene, and then delete it,
Leaving it for about three or four hours had no effect on FPS and latency, and there was no significant difference in volume of js VN runtime, or Memory size.
(Of course, if you don't destroy the sprite it seems like you keep using the memory)

Until I tested it like this, I definitely thought there would be a stack of bitmap / cache file garbage as you said, but in reality, the built-in memory managing seems to be working hard. It's amazing to me, too.
I post a summary of the code here just in case anyone is wondering,

Spoiler: Code
Code:
    class MessageBubbleManager {
        
        static initialize() {
            this._queue = [];
        }
        
        static add_MessageBubble(message) {
            var _message = message;
            var new_MessageBubble = new MessageBubble(_message);
            this._queue.push(new_MessageBubble)
        }
        
        static remove_MessageBubble(bubble) {
            for (var i = 0; i < this._queue.length; i++) {
                if (this._queue[i] == bubble) {
                    this._queue.splice(i, 1);
                }
            }
        }
        
        static _giveOrder() {
            for (var i = 0; i < this._queue.length; i++) {
                this._queue[i]._order = i;
            }
        }
    }
    
    class MessageBubble extends Sprite {
        constructor(message) {
            super();
            this._order = 0;
            this._state = "";
            this._message = message;
            this._duration = 200;
            this._timer = 0;
            this._bitmap = "";
            this._x = 0;
            this._y = 0;
            
            this._init();
        }
        
        _init() {
            this._messageWidth = this.calculateEffectiveLength(this._message);
            this._bitmap = ImageManager.loadPicture("UI/messageBubble_s");
            this._bitmap.addLoadListener(() => {
                this._body = new Sprite(this._bitmap);
                this._body.anchor.set(0.5);
                
                this._text = new Sprite(new Bitmap(this._body.width, this._body.height));
                this._text.bitmap.drawText(this._message, 0, 0, this._body.width, this._body.height, 'center');
                this._text.anchor.set(0.5);
                
                this.addChild(this._body);
                this.addChild(this._text);
                SceneManager._scene.addChild(this);
                
                this._updatePosition();
            });
        }
        
        update() {
            this._timer += 1;
            
            this._updatePosition();
            this._updateAnimation();
            
            super.update();
        }
        
        _updatePosition() {
            MessageBubbleManager._giveOrder();
            
            var padding = 4;
            var margin = 6;
            var heightUnit = this._body.height + margin;
            var targetPosX = Graphics.width - (this._body.width / 2) - padding;
            var targetPosY = (this._order + 0.5) * heightUnit + padding;
            
            this.x = targetPosX;
            this.y = this.y * 0.9 + targetPosY * 0.1;
            this._x = this.x;
            this._y = this.y;
        }
        
        _updateAnimation() {
            //simpleFade in out animation with opacity and scale
            var animationTiming = this._timer/ this._duration;
            var animationMultiplier = Math.max( (30 - this._timer) / 30, 0 );
            this.scale.x = 1 + Math.sin(animationMultiplier * Math.PI * 5) * animationMultiplier * 0.1;
            this.scale.y = 1 + Math.cos(animationMultiplier * Math.PI * 5) * animationMultiplier * 0.1;
            if (this._timer >= this._duration - 20) {
            this.opacity -= 255 / 20;
            }
            if (this.opacity <= 0) {
                MessageBubbleManager.remove_MessageBubble(this)
                this.destroy();
            }
        }
    }

Thanks!

Original thread: https://forums.rpgmakerweb.com/threads/solved-need-help-for-making-message-bubble-function.170241/