Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

C# get variable from another script

Discussion in 'Scripting' started by DaReign, Oct 9, 2013.

  1. DaReign

    DaReign

    Joined:
    Apr 12, 2013
    Posts:
    79
    Hi

    I've two scripts
    and second

    I try access totalTime variable from RaceManager in StageManager script.
     
    LFG1 likes this.
  2. image28

    image28

    Joined:
    Jul 17, 2013
    Posts:
    457
    Dunno if this is what is wrong but you could try changing

    Code (csharp):
    1.  
    2.  racemanager = GetComponent<RaceManager>();
    3.  
    to

    Code (csharp):
    1.  
    2. racemanager = gameObject.GetComponent<RaceManager>();
    3.  
    if the stage manager script is inside the same gameobject as the racemanager script... if it is not you will have to use GameObject.Find or FindWithTag like you did in the line above.

    Code (csharp):
    1.  
    2. racemanager = GameObject.Find("Racemanager").GetComponent<RaceManager>();
    3.  
    if it fails to find the object or script when you try to set totalTime in the next line it should get a NullReference exception.

    Also watch out for case sensitivity.
     
    chon59 likes this.
  3. Dejan1

    Dejan1

    Joined:
    May 5, 2013
    Posts:
    13
    Make public static float totalTime;
    Then you can acces AND change this variable globaly from any other script.
    In your case call totalTime from StageManager script like this:
    RaceManager.totalTime

    if you change it like this: RaceManager.totalTime=5; it will be changed globally(both in RaceManager and StageManager script)
     
    ibulut likes this.
  4. jvil

    jvil

    Joined:
    Jul 13, 2012
    Posts:
    263
    Please don't do that, it's really a bad idea.

    Use GetComponent as someone said on previous post.
     
    Damerek likes this.
  5. Dejan1

    Dejan1

    Joined:
    May 5, 2013
    Posts:
    13
    All my global variables are static and everything works perfectly. This would not be allowed if it warent useful.
     
  6. jvil

    jvil

    Joined:
    Jul 13, 2012
    Posts:
    263
    Okay. Good luck with your project.
     
  7. Dejan1

    Dejan1

    Joined:
    May 5, 2013
    Posts:
    13
    Likewise.
     
  8. doubleJ

    doubleJ

    Joined:
    Feb 10, 2013
    Posts:
    33
    Instead of fighting each other, maybe it would be better to explain your position guys?

    I presume what jvil tried to say is that using public static (aka global variables) is just bad programming habit. The main problem with global variables is that they violate OOP principles of encapsulation which is always not good. They can always result in unexpected problems with you code (side effects) and they make testing quite "painful".

    On the other hand there are examples when global variables are useful. One of those examples are constant values, which usually end up being global variables.

    I hope this tread will help you in the future. :cool:
     
  9. jvil

    jvil

    Joined:
    Jul 13, 2012
    Posts:
    263
    This topic has already been discussed so many times.

    Set all variables to static it's a common pitfall for newbie developers.

    There are good reasons for use static variables, but when you set all your variables into static it's a sign you have no idea what you're doing.

    So, no matter if you told them about permanent memory consumption, data encapsulation, concurrency, make code easy to mantain, and more stuff, they will continue to do it.

    Just check the code of any decent open-source app and see how many static variables they are using, then ask yourself why you're using so many static variables and someone experienced developing apps don't.
     
  10. Dejan1

    Dejan1

    Joined:
    May 5, 2013
    Posts:
    13
    If any of your variable needs to be globaly accesed and changed, make it static. Use lock if neccesary. Simple as that.
     
    Last edited: Oct 10, 2013
  11. jvil

    jvil

    Joined:
    Jul 13, 2012
    Posts:
    263
    $Facepalm_227785.jpg
     
  12. Dejan1

    Dejan1

    Joined:
    May 5, 2013
    Posts:
    13
    Take your time, no rush.

    Ok, here is a valid question.
    We have a global static variable "something".
    If script1 is accesing this variable the same time as script2 trys to change it, can script1 prevent script2 from changeing the variable.Anyone is welcome to answer.
     
    Last edited: Oct 10, 2013
  13. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    The question is moot in the context of MonoBehaviour derivatives and a large chunk of Unity-specific programming anyway because the application is single-threaded. You're skewing the argument away from the usage of static variables and towards the concept of thread safety.
     
  14. Dejan1

    Dejan1

    Joined:
    May 5, 2013
    Posts:
    13
    So, it won`t prevent it. Thanks.
    This was no argument, I really was worried :)
     
  15. image28

    image28

    Joined:
    Jul 17, 2013
    Posts:
    457
    The only time I use static variables is when I need to access them from a different scene.... I know there is a better way, but I haven't started using it yet. I try to keep those variables to a bare minimum..
     
  16. Dejan1

    Dejan1

    Joined:
    May 5, 2013
    Posts:
    13
    Sure. Health value,inventory etc..
    One could go through - get_componnent - methods to check for variables changes in other scripts and then updateing them constantly, but why do that when static variables give you a direct acces to modify these variables.
     
  17. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Because static variables don't give you any encapsulation or state. Anything in your application could change them from anywhere at anytime and it'd be very difficult to track down. Generally speaking, jvil was correct - static variables are not ideal for situations like the ones you mentioned.
     
  18. Dejan1

    Dejan1

    Joined:
    May 5, 2013
    Posts:
    13
    Anything from my application ?
    If it`s my application then I decide what is public ,private ,static etc.
    Anyway, I was reffering to single player applications.Generally speaking, it is best to use static variables in them.
     
  19. melaz

    melaz

    Joined:
    Oct 29, 2013
    Posts:
    2
  20. Aarlangdi

    Aarlangdi

    Joined:
    Nov 27, 2013
    Posts:
    1
    Last edited: Apr 22, 2014
  21. L2o

    L2o

    Joined:
    Apr 11, 2014
    Posts:
    1
  22. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    Generally speaking, it is possible to successfully write a single player app using them. That doesn't mean it is best to use static variables. No one has a problem with you using them in your app, but its not a good idea to advise a beginner to use them all over his app, because except for in specific scenarios, using them in such a widespread manner is bad design and can cause serious issues, especially as a project grows.
     
  23. Arahan Imon

    Arahan Imon

    Joined:
    Jul 29, 2013
    Posts:
    3
    I saw all the questions and answer regarding static variables,i understand that static variables are not good for programming,thanks all but i have question that if static variable violates OOP principle then why static keyword still presents in OOP Paradigm and if it useful in some programming situation then how can i describe that where the static variable should be used,please give some examples any help will be appreciated.
     
    Epic_Pencil and astracat111 like this.
  24. Epic_Pencil

    Epic_Pencil

    Joined:
    Dec 29, 2016
    Posts:
    1
    I tried this and it isn't working. I'm not sure whether the problem is that the values aren't being passed, therefore the vector is not overwritten, or if the vector is not being properly referenced, therefore the values aren't being passed. See below.

    I have this method in class BehaviorController:

    //Further up
    RandomWander randomwander;
    float new_x = 0;
    float new_y = 0;
    float new_z = 0;

    void WhenInRange () {


    if ((Person1position - Playerposition).sqrMagnitude <= Distance*Distance) {
    Material1.SetColor("_Color", UnityEngine.Color.red);

    randomwander = gameObject.GetComponent<RandomWander>();
    randomwander.movement.Set(new_x, new_y, new_z);

    }

    }

    And in RandomWander:

    phys.AddForce(movement);

    But it doesn't seem to be overwriting the vector. Interestingly, it's also saying that floats x-z are assigned but not used. I'm pretty sure there's a connection between these two things, as I see it I'm using new_x... z in randomwaner.movement.Set so I don't know why it thinks I'm not.
     
    Last edited: Dec 29, 2016
  25. SuperGamer583

    SuperGamer583

    Joined:
    Dec 3, 2017
    Posts:
    1
    Sorry for bumping.

    ScriptName AnyText = GetComponent<ScriptName>();


    For example:
    RaceManager raceManager = GetComponent<RaceManager>();

    Also it can only be used in Void you typed it in, so if you created it in Start() you can't use it in Update() , you have to insert the same code to the Update() to make it work.


    So the code for RaceManager is:

    using UnityEngine;
    using System.Collections;

    public class RaceManager : MonoBehaviour
    {
    public float totalTime=100;

    void Start()
    {
    StageManager stageManager = GetComponent<StageManager>();
    }

    void Update()
    {

    }


    }



    And for StageManager:

    using UnityEngine;
    using System.Collections;

    public class StageManager : MonoBehaviour
    {
    public int lapsNumber=2;
    public float startTime=0;
    public float stageTime=0;
    public float totalRaceTime=0;


    void Start()
    {
    RaceManager raceManager = GetComponent<RaceManager>();
    startTime = Time.time;
    //totalRaceTime =
    totalRaceTime = raceManager.totalTime;
    Debug.Log("totaltime"+totalRaceTime);

    }


    void Update()
    {
    stageTime = Time.time - startTime;
    Debug.Log("totaltime"+totalRaceTime);
    }


    void OnGUI()
    {
    // Make a background box
    //GUI.Box(new Rect(Screen.width,10,100,90), "Loader Menu");
    // GUI.Box (Rect (Screen.width,0,0,0), "Loader Menu");
    GUI.Box (new Rect (0,0,Screen.width,50),"");
    //GUI.Label(new Rect(0, 0, 150, 150),"Stage time "+stageTime.ToString());
    GUI.Label(new Rect(0, 0, 150, 150),"Race time "+(totalRaceTime+stageTime).ToString());

    //GUI.Box (new Rect (Screen.width - 100,Screen.height - 50,100,50), "Bottom-right");
    // GUI.Label(new Rect(Screen.width - 100, Screen.height - 50, 100, 50),"Stage time "+stageTime.ToString());

    }



    }
     
    Last edited: Dec 15, 2017