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 would you call a variable from another class

Discussion in 'Scripting' started by Sean-Powell, Jan 16, 2015.

  1. Sean-Powell

    Sean-Powell

    Joined:
    Dec 18, 2014
    Posts:
    87
    i have a variable in another class that i wish to change it is public but i can not find any way of calling it. How do you do this?
     
  2. jorgemk85

    jorgemk85

    Joined:
    Jun 24, 2013
    Posts:
    16
    Make an instance of the class that's gonna change the value inside the class that will use it and change the value of your public variable. Something like this:

    Code (CSharp):
    1. private ClassWithPublicVariable myClass = new ClassWithPublicVariable();
    2.  
    3.  
    4. void Start()
    5. {
    6.     myClass.MyPublicVariable = 0;
    7. }
     
  3. DRRosen3

    DRRosen3

    Joined:
    Jan 30, 2014
    Posts:
    682
    Actually this isn't completely accurate. This will let you access the variable (but it doesn't change it at run-time).

    If you want to access a variable that's currently in play, then you first need to reference the GameObject that the script that has the variable is attached to. For example, if player A fires a bullet at player B, and I want to take health away from player B, doing it the way that @jorgemk85 suggested won't work. You'd have to do something like...

    Code (CSharp):
    1. void Update(){
    2.    GameObject playerB = FindGameObjectWithTag("PlayerB");
    3.    PlayerHealthScript playerBHealth = playerB.GetComponenet<PlayerHealthScript>();
    4.    if(/*Put your condition here for if the bullet hits or not.*/){
    5.       playerBHealth.playerHP -= damage;
    6.    }
    7. }
     
    Deleted User likes this.
  4. jorgemk85

    jorgemk85

    Joined:
    Jun 24, 2013
    Posts:
    16
    It seems like my programming example got misunderstood... It was just an example of how to change a value of a public variable since the OP doesn't seem to know how at all...

    Anyway, hope your approach helps outlaw1148.
     
  5. DRRosen3

    DRRosen3

    Joined:
    Jan 30, 2014
    Posts:
    682
    No worries, I just wanted to make sure to cover all bases.