[SOLVED] Help with calling Methods/Functions

I’m attempting to update the game score every time an enemy is destroyed. I have a script for the UI as shown below:

var ScoreUpdate = pc.createScript('scoreUpdate');

// initialize code called once per entity
ScoreUpdate.prototype.initialize = function() {
    
            this.score = 0;
    
    var onScoreupdate = function() {
    this.score = this.score + 50;   
    };
    
        this.app.on('player:score', onScoreupdate);
    
    });

};

// update code called every frame
ScoreUpdate.prototype.update = function(dt) {
    
this.entity.element.text = this.score;
    
};

Here is the script that fires the method from a collision Trigger script:

var Trigger = pc.createScript('trigger');

// initialize code called once per entity
Trigger.prototype.initialize = function() {

    this.entity.collision.on('triggerenter', this.onTriggerEnter, this);
        this.app.fire('player:score');
};

// update code called every frame
Trigger.prototype.update = function(dt) {
    
            if (this.app.timeScale == 1) {
                   this.entity.translate(0, 0, -0.1);
            }

};

Trigger.prototype.onTriggerEnter = function (result) {
        result.enabled = 0;

        this.entity.enabled = 0;        
};

Any help would greatly be appreciated. Thanks! I’ve also placed the fire event right before the result.enabled line and it doesn’t change the score.

Hi @MikeTheTech

For optimization purposes, you should have this outside of the update function.

this.entity.element.text = this.score;

I am a little confused by this logic, but maybe you should fire the event inside the trigger function, not inside initialize, from my perspective this doesn’t make any sanse.

this.app.fire('player:score');

You should write code this way

ScoreUpdate.prototype.initialize = function() {
         this.score = 0;
        this.app.on('player:score', onScoreupdate,this);
};
ScoreUpdate.prototype.onScoreupdate=function(value)
{
   this.score+=value;
   this.entity.element.text=this.score;
};

Also maybe it’s for the best if you make one Score manager, which will contain text as property, so you can use it in any new project.

2 Likes

Thank you so much! It worked great. :slight_smile: