Search Unity

checking a var based on input from inspector

Discussion in 'Scripting' started by Falin, Oct 22, 2012.

  1. Falin

    Falin

    Joined:
    Sep 29, 2009
    Posts:
    242
    Is it possible to make a script check a var from an other script by entering the var name in the inspector?

    Example:

    Inspector:
    Code (csharp):
    1. Script [Drag script here]
    2. Var That Needs to be checked: [enter var name here]
    3. Outcome Var: [enter the outcome of the var]
    in code:
    Code (csharp):
    1. if(Script.VarThatNeedsToBeChecked == OutcomeVar)
    2. {
    3.     //Do Something
    4. }
     
  2. Charabis

    Charabis

    Joined:
    Nov 5, 2009
    Posts:
    203
    I don't believe this is possible as there is no var type in the inspector. Sure they ARE vars, but they get changed to something appropriate when used. For instance, if you put a whole number in, it behaves like an int. In your case, you would be putting in what it identifies as a string, so that's what it would be.

    HOWEVER, if there's only a limited number of options it could be, then you could simply create a switch-case setup to test the strings against the cases to find the right variable to get. Even better, you can use an enumeration and create the inspector entry as an enumeration of that variable which also ensures you don't enter it wrong as it becomes a simple selection.
     
    Last edited: Oct 22, 2012
  3. Falin

    Falin

    Joined:
    Sep 29, 2009
    Posts:
    242
    thanks for the answer
     
  4. Loius

    Loius

    Joined:
    Aug 16, 2012
    Posts:
    546
    It's better to use Charabis's answer, but yes, you can, using eval.

    Code (csharp):
    1. var varToCheck : String;
    2. var aVar : boolean;
    3.  
    4. function Check() {
    5.   var result : boolean;
    6.   eval("if( " + varToCheck + ") result = true");
    7. }
    Keep in mind that eval is a security risk (since it's easy to read strings), so don't use it extensively if you're worried about data security.
     
unityunity