Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to acces a variable from another script

Discussion in 'Scripting' started by dafuq313, Sep 15, 2016.

  1. dafuq313

    dafuq313

    Joined:
    Mar 29, 2016
    Posts:
    26
    I found this on internet http://answers.unity3d.com/questions/42843/referencing-non-static-variables-from-another-scri.html
    And my question is next : what means these lines of code ?
    1. GameObject thePlayer =GameObject.Find("ThePlayer");
    2. PlayerScript playerScript = thePlayer.GetComponent<PlayerScript>();
    3. playerScript.Health-=10.0f;

    I did manage to acces the variable very easy by making it static and just writing ThatClass.variable
    But those lines of code got my interest,if you can simply acces a variable just by ThatClass.variable,what those lines of code from above mean ?
     
  2. CrymX

    CrymX

    Joined:
    Feb 16, 2015
    Posts:
    179
    a static member is the same value for every object of the class.

    if you have two character, you can't use a static member for the health because if you modify the value of the static member, it's modified for every object.

    So in the code above :

    1 : you get the player object
    2 : You get the script "PlayerScript"
    3 : you modify the health of the specific player

    i can take another exemple :

    in my game everygun has the same damage so i can declare "damageGun" a static member.
    My guns have different magazine size, so the "magazineSize" should be a not static member.
     
    dafuq313 likes this.
  3. dafuq313

    dafuq313

    Joined:
    Mar 29, 2016
    Posts:
    26
    O i get it thanks
     
    CrymX likes this.