Search Unity

Help! Accessing variables on the fly...

Discussion in 'Scripting' started by sbuchbinder, Apr 30, 2008.

  1. sbuchbinder

    sbuchbinder

    Joined:
    Apr 4, 2008
    Posts:
    53
    Basically I'm trying to get reference to a variable within the same script, but I'm not sure if I can go about it this way:

    I have 3 GameObjects: startPos1, startPos2, startPos3.

    I just want to pass in a number (1,2,or3) to create a variable the refernces the appropriate gameObject var.

    In flash it would be something like:

    setVar(1);

    function setVar(n:Number)
    {
    var activeObj = this["startPos" +n];
    }

    I'm not sure how to go about doing this in javascript though...
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Easiest and fastest is to not try constructing names like that, but use an array instead.

    Code (csharp):
    1. var startPos : GameObject[];
    Then you refer to the desired one like "startPos[0]", "startPos[1]", etc. Although given the name of the variable, it's likely it would be a little more convenient to define it as Transform rather than GameObject.

    --Eric