Uncaught TypeError: Cannot read property 'on' of undefined (help)

I am trying to move pipes depending on what random number is generated:

        app.on('pipe:relocate', function () {
            

        var rnd = Math.random();
        var item = this.app.root.findByName('Pipes');
        this.far = [];

        if (rnd > 0 < 0.33) {
            var pos2;
            pos2 = this.item.getLocalPosition();
            this.item.setLocalPosition(1, pos.y, pos.z);
        }
        if (rnd > 0.33 < 0.66) {
            var pos3;
            pos3 = this.item.getLocalPosition();
            this.item.setLocalPosition(2, pos.y, pos.z);
        }
        if (rnd > 0.66 < 1) {
            var pos4;
            pos4 = this.item.getLocalPosition();
            this.item.setLocalPosition(3, pos.y, pos.z);
        }
    }, this);

    app.fire('pipe:relocate');

There error is in the first line, but I don’t know how to fix this? I have tried to inspect and debug but I have not found a solution,
Thanks :slight_smile:

Normally if you are running this in the context of a script method, you need to use this.app.on instead of app.on. You should debug the app variable and see if it is defined or not, that’s what the error is pointing out.

Also, your if expressions aren’t correct, you can’t have multiple comparing expressions together without using and/or. Here is how that should look:

        if (rnd > 0 && rnd < 0.33) {
            var pos2;
            pos2 = this.item.getLocalPosition();
            this.item.setLocalPosition(1, pos.y, pos.z);
        }
        if (rnd > 0.33 && rnd < 0.66) {
            var pos3;
            pos3 = this.item.getLocalPosition();
            this.item.setLocalPosition(2, pos.y, pos.z);
        }
        if (rnd > 0.66 && rnd < 1) {
            var pos4;
            pos4 = this.item.getLocalPosition();
            this.item.setLocalPosition(3, pos.y, pos.z);
        }

Thanks! I have successfully debugged my code.
Also thank you for fixing my if expressions :smiley:

1 Like