[SOLVED] Access array variable from another script


I have two scripts and want to access a variable that is a array from one script in the other script.
The Script with the Array is based on the Tuturial(Camera following a path | Learn PlayCanvas). I need the pos_liste_pos from that script.

CameraPathScroll.prototype.createPath = function () {

    //rest of the CameraPath Script

    var pos_liste = [];
    for (i = 1; i < nodes.length; i++) {
        var prevNode = nodes[i-1];
        var nextNode = nodes[i];
        // Work out the distance between the current node and the one before in the path
        distanceBetween.sub2(prevNode.getPosition(), nextNode.getPosition());
        pathLength += distanceBetween.length();
    for (i = 0; i < nodes.length; i++) {
        // Calculate the time for the curve key based on the distance of the path to the node
        // and the total path length so the speed of the camera travel stays relatively
        // consistent throughout
        var t = nodePathLength[i] / pathLength;

        var node = nodes[i];

        var pos = node.getPosition();
        this.px.add(t, pos.x);
        this.py.add(t, pos.y);
        this.pz.add(t, pos.z);


        // Create and store a lookAt position based on the node position and the forward direction
        var lookAt = pos.clone().add(node.forward);
        this.tx.add(t, lookAt.x);
        this.ty.add(t, lookAt.y);
        this.tz.add(t, lookAt.z);
        var up = node.up;
        this.ux.add(t, up.x);
        this.uy.add(t, up.y);
        this.uz.add(t, up.z);

    var pos_liste_pos = pos_liste; // this array I need for my other script

    console.log(pos_liste + "list");

And want to include it in these script:

Position.prototype.onUpdate = function(dt) {

    var CameraPathScrollScript =  pc.app.root.findByName('Camera').script.CameraPathScroll;
    var checkpointPositions = CameraPathScrollScript.pos_liste_pos;
    console.log(checkpointPositions); // this results undefined

The scripts are both attached to the same entity named Camera.
Can someone help me to solve this problem?

Hi @le601 and welcome.

As far I can see the variable is currently not accessible from outside the function.

To make it accessible you need to create the variable in the initialize function of the script, like this.pos_liste_pos = null;. After that, you also need to use this.pos_liste_pos instead of pos_liste_pos in your function.

Thanks, that solved the problem. Now it works

1 Like