Call function from a NON-Preload Script

Hi!
I am using Firebase Analytics.
I have Initialised firebase successfully :slight_smile:
I made a custom function to send analytics, but my script is not pre loaded. So I can’t access that function.

Please help me call the function from my NON-Preload Script.
Or please guide me how to send Firebase Analytics.

Thanks :blush:

Here is my scripit

var TestAna = pc.createScript('testAna');

// initialize code called once per entity
TestAna.prototype.initialize = function() {
  
this.sendAnalytics("Game_Initialized");
};

// update code called every frame
TestAna.prototype.update = function(dt) {

};

TestAna.prototype.sendAnalytics = function(anaToSend){

    logEvent(analytics, anaToSend);
}; 

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.6.11/firebase-app.js';

// If you enabled Analytics in your project, add the Firebase SDK for Google Analytics
import { getAnalytics, logEvent } from 'https://www.gstatic.com/firebasejs/9.6.11/firebase-analytics.js';

// TODO: Replace the following with your app's Firebase project configuration
  const firebaseConfig =
 {
   apiKey: "AIzaSyAR3pJ7Okay-kHJnQg8op68J0vQJFXNik8",
    authDomain: "playcanvas-12629.firebaseapp.com",
    projectId: "playcanvas-12629",
    storageBucket: "playcanvas-12629.appspot.com",
    messagingSenderId: "193789163146",
    appId: "1:193789163146:web:f1fa3ee06743c9ab625f73",
    measurementId: "G-YNFHSTQM79"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const analytics = getAnalytics(app);

Basically I want to call this function from any of my scripts

Unfortunately you cannot call a function from a script unless it has been loaded. If you want to be able to call the function, you can simply check if its script has been loaded, and if it hasn’t, you can load it, then call the function.

It might look like this:

var script = this.app.assets.find('my-script.js');
if (!script.loaded) {
    this.app.assets.load(script);
}

Its noteworthy that the script won’t necessarily load right away. For this reason, you should use script.ready(callback), that calls a function once the asset has been loaded. You can read more about this here.

Thanks :blush:

I’m looking into it