Search Unity

  1. The 2022.1 beta is now available for testing. To find out what's new, have a look at our 2022.1 beta blog post.
    Dismiss Notice

Using Int variables between 2 scripts

Discussion in 'Getting Started' started by claize, Nov 27, 2021.

  1. claize

    claize

    Joined:
    Jul 5, 2021
    Posts:
    2
    I know that in my case I could as well write the classes together in 1 script, but I wanna learn how to link up 2 scrips properly.
    Button 1 with scipt A: Increases the variable int scoreA by +1 each time it is clicked.
    Button 2 with script B: Does the very same (int scoreB raised +1)
    Button 3 with script C: should compare scoreA and scoreB.

    I cannot figure out how to get the actual/adjusted values of the 2 variables scoreA and scoreB into the third script.(script C)
     
  2. frasderp

    frasderp

    Joined:
    Oct 6, 2016
    Posts:
    19
    There are a few ways to do this.

    One example

    Code (CSharp):
    1. public void Start()
    2. {
    3.     gameObject.Find("NameOfTheGameObjectTarget").GetComponent<NameOfTheScript>().NameOfTheProperty = ...;
    4. }
    Where NameOfTheGameObjectTarget would be Button 1 and 2, NameOfTheScript is self explanatory, and then NameOfTheProperty would be the Scores.

    Another option, instead of using gameObject.Find is to declare these in Script 3 (for example, "public GameObject Script 1" and then assigning the gameobject in the Inspector screen for the gameobject Script 3 is attached to).
     
unityunity