how would you call a variable from another class

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?

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:

private ClassWithPublicVariable myClass = new ClassWithPublicVariable();


void Start()
{
    myClass.MyPublicVariable = 0;
}

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…

void Update(){
   GameObject playerB = FindGameObjectWithTag("PlayerB");
   PlayerHealthScript playerBHealth = playerB.GetComponenet<PlayerHealthScript>();
   if(/*Put your condition here for if the bullet hits or not.*/){
      playerBHealth.playerHP -= damage;
   }
}
1 Like

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.

No worries, I just wanted to make sure to cover all bases.