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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Change variables in other script

Discussion in 'Scripting' started by CodeWurm, Aug 5, 2016.

  1. CodeWurm

    CodeWurm

    Joined:
    Nov 8, 2014
    Posts:
    316
    Oke so I searched on internet for examples how to change variables in other scripts I just need a little bit more help to understand and to make it clear for myself.

    I have this code:

    Code (CSharp):
    1. if (col.gameObject.name == "Grond")
    2.         {
    3.             Main Camera.GetComponent<Score>().leven --;
    4.         }
    This code is written in script 1 attached to the ball.
    When the ball touch the ground I want the lifes from the script attaced to the main camera to decrease by one.
    How do I write it down the right way because this one gives me a parsing error.
     
  2. GNGification

    GNGification

    Joined:
    Oct 24, 2013
    Posts:
    59
    On phone atm. Can't check this.

    That seems about right, but I'm not sure if you can write it like Main Camera with a space, unless this is some unity thing im not aware of.

    I would try crearing a variable and then adding the camera to it and using it like

    variable.GetComponent<script>().variableToChange--;

    I might be wrong or there may be a better way, but give it a try.
     
  3. RavenOfCode

    RavenOfCode

    Joined:
    Apr 5, 2015
    Posts:
    869
    Also on phone.

    You need to use the reference to change the variable. What I would suggest is something like this:
    Code (CSharp):
    1. public BallScript bS;
    2.  
    3. void DoSomething ()
    4. {
    5. bS.HitGround();
    6. }
    Then just assign bS in the inspector to the ball script on the ball.
     
  4. TaleOf4Gamers

    TaleOf4Gamers

    Joined:
    Nov 15, 2013
    Posts:
    825
    should be:
    Code (CSharp):
    1.         if (col.gameObject.name == "Grond")
    2.         {
    3.             Camera.main.transform.gameObject.GetComponent<Score>().leven --;
    4.         }
    5.