Search Unity

accessing variables from another script

Discussion in 'Scripting' started by BetrayedPickle, Jun 1, 2020.

  1. BetrayedPickle

    BetrayedPickle

    Joined:
    Mar 30, 2019
    Posts:
    119
    So I have a Pick-Up script that when you click on an object, it deletes itself and sets the boolean IngredientCollected to true. Now I am making a script that basically says "If IngredientCollected equals true (which I is the variable that I need help accessing) then make a little UI pop up. How can I access the IngredientCollected variable in this new script?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,749
    The narrow-case example of reaching a variable in another script is to make it public and give the accessor a reference to that script instance.

    The broader-case solution is to use a GameManager that keeps track of all state that needs to be shared between multiple disparate subsystems.
     
  3. BetrayedPickle

    BetrayedPickle

    Joined:
    Mar 30, 2019
    Posts:
    119
    I know how to make it public but how do you give the reference?
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Look at your script's Inspector pane, and drag your target object into the slot that appears there.
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,749
    With another public variable.

    Let's say ScriptB wants to access variable Foo in ScriptA.

    ScriptA: has a public variable called Foo

    ScriptB: has a public variable of type ScriptA (the reference to ScriptA) to let it access Foo

    In the editor you drag the ScriptA reference into the ScriptB slot in the inspector.

    Now ScriptB can access Foo using the ScriptA reference.
     
  6. BetrayedPickle

    BetrayedPickle

    Joined:
    Mar 30, 2019
    Posts:
    119
    Thanks, that worked for me!!
     
  7. BetrayedPickle

    BetrayedPickle

    Joined:
    Mar 30, 2019
    Posts:
    119
    Thanks, that worked for me!!