Where In Script Can This, Ui(), Scene(), Etc., Be Used?

Discussion in 'Technical Discussion' started by Jay Jennings, Dec 28, 2019.

  1. Jay Jennings

    Jay Jennings Boxer

    Dec 19, 2019
    Likes Received:
    [First, it would be really nice if there was a specific section in the forum for scripting questions -- that way people who *only* want NoCode don't ever have to see script stuff -- and those of us who are code geeks would have a place to play.]

    Here's my scripting problem...

    Code that I've written works when inside the signal() function, but in trying to clean things up I broke some code out into their own functions that are called from inside signal() -- and the code stopped working. It's saying things like, "this.ui is not a function" but it's the same code that worked inside signal().

    So I thought maybe I could create some global variables outside of any function:
    var _this
    var _ui
    var _scene
    var _ent
    ...and then initialize them inside the init() function so I could then use them later:
    function init() {
        _this = this
        _ui = this.ui()
        _scene = this.scene()
        _ent = this.entity()
    ...but no joy -- inside the other functions _this sometimes works (not sure), but _ui, for example, just shows as null.

    Can anybody shed some light on what's happening here? I would expect to be able to set a global variable inside init that would then be available throughout the life of that entity. Or maybe a script component goes in and out of life???
  2. Hi Jay! You pose a good question here. The issue is that the keyword `this` is defined differently in a custom function vs the built-in functions. Here's some solutions you can try.

    1. Use `component` keyword
    Outside of the built-in functions in a script, if you need to use `this` you can use `component` instead.

    function init(){
    function foo(){
       log(component.ui()); // same result as this.ui() inside init()
    2. Global variable _this
    I believe your global variable solution will work if you initialize `_this = this` in init(), then in your custom function use `_this.ui();` etc
    let _this;
    function init() {
       _this = this;
    function foo(){
    I hope that helps!
    Last edited by a moderator: Jan 6, 2020
    Vlad-NY and Sean Buildbox like this.
  3. montasli

    montasli Boxer

    Nov 14, 2020
    Likes Received:
    Thanks Workes Perfectly.

Share This Page