Home>

In Unity, when you open the script, the firstStart ()With functionsUpdate ()There is a function,Start ()I don't know how to use the function. There is a site that says that it is used for initializing variables, etc.Start ()If i define a variable inUpdate ()I can't use it inside ...
It's a simple question, but I would appreciate it if anyone could answer it.

  • Answer # 1

    If you define a variable in Start (), you cannot use it in Update ()

    Variable with start functionDeclarationThen you can certainly not use it, but if you just initialize it, you can also use it in the update function.
    There are various ways to use it, such as caching by Find and defining the initial position of movement.

    // Initialize with Start function and cache
    GameObject me;
    void Start () {
        me = this.gameobject;
    }
    void Update () {
        me.transform.position = new Vector3 (1, Random.Range (1,10), 1);
    }
    // In this case it is meaningless.
    void Start () {
        GameObject me = this.gameobject;
    }
    void Update () {
        me.transform.position = new Vector3 (1, Random.Range (1,10), 1);// Error because me is not defined
    }

    Perhaps the scope of variables is ambiguous, so I think it's a good idea to take a closer look at that area.