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

Trying to use a variable from another script (attached to same object)

Discussion in 'Scripting' started by Darkmyst, Jan 11, 2015.

  1. Darkmyst

    Darkmyst

    Joined:
    Aug 3, 2013
    Posts:
    35
    I have two diagramed images to explain my dilemma. Basically, i want to have a gui display the players total deaths, which is in another script. i have spent a while experimenting but i just can't seem to get it to work and many videos i come across explain different, conflicting methods.

    Here are my questions:
    - What is the best way to use variables from another script in unity (C#)?
    - What am i doing wrong
    - Have i f*cked up anything else in my script (new to C# in unity as you can guess).

    Images:
    whydidimakethissofancylookin.jpg
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    If the other script is on another object, the simplest method is to put a public Gameobject variable on the script that needs to read the other one. Then drag the other GameObject onto that one in the editor. Then in the start menu, you use gameObjectName.GetComponent<scriptName>().variableName.
     
    Kiwasi likes this.
  3. Darkmyst

    Darkmyst

    Joined:
    Aug 3, 2013
    Posts:
    35
    I'm a little confused about what i really should be doing, if my script is on the same object do i need to do this. Would you be able to show me a little example code just to help me understand. :)
     
  4. ensiferum888

    ensiferum888

    Joined:
    May 11, 2013
    Posts:
    317
    In your HealthGUI script you got the variable declaration in the wrong order or you forgot to capitalize the variable type.

    It's access_type - type(name of class) - name(name of variable) so the declaration should be:

    Code (CSharp):
    1. //The variable named _collision is of the Collision type.
    2. public Collisions _collisions
    3.  
    4. void Start(){
    5.     //Just calling GetComponent implicitly calls gameObject.GetComponent I believe,
    6.     ///You still need to call this even if it's on the same gameobject.
    7.     _collisions = GetComponent<Collisions>();
    8. }
    9.  
    10. //Your Label won't show up if you put the GUI code inside Update, you need to put it inside the OnGUI method.
    11. void OnGUI(){
    12.     GUI.Label(new Rect(25, 25, 100, 30), _collisions.deaths.ToString());
    13. }
    14.  
    15.