Accessing variables from other scripts

Updated on February 6, 2016 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
5 on February 5, 2016

Hi everyone,

I looked this up but it never fully works for some reason and it’s not 100% clear to me.
I am in script “A” and I want to access and change the value of a variable (an integer) which is stored in script “B”. Script A is a component of a game object in the scene and script B is a component of a prefab. How can I do this? I saw GetComponent is often used but when is GameObject.Find(…).GetComponent<…>() used and when is gameObject.GetComponent<…>() used? Is it when Script B is attached to a different game object compared to Script A? How do I do this whole thing, please help.

Thx in advance!

  • Liked by
1 on February 5, 2016

I’ll explain this as in HEALTH on a player.

We have a script called “Script_A”.
Within that script we have an int called “currentHealth”
public int currentHealth;

Over in script “Script_B”, we want to access currentHealth.
So in order to do this, i’ll name a int called player_life.
private int player_life;

I’ll access currentHealth and pull it into player_life.

This would go in script B.
player_life = GetComponent<Script_A>().currentHealth;

This basically told player_life to get the component of Script_A, and find the int
currentHealth that we had setup there. Now in script B, player_life is whatever
currentHealth is in Script_A. By doing that, you’ll notice whenever you type the 
GetComponent<Script_A>(). portion, you’ll see ALL of the information from
Script_A pop up.

Hopefully this helps and I didn’t go overboard with trying to simplify it.

on February 5, 2016

Good explaination!
But there’s more:
GetComponent is the same as gameobject.GetComponent.
They both get a component on the same gameobject that the calling script is on.
If you want to get a component on another gameobject, then do something like this:

public GameObject MyObject; // Assign this in the inspector
public void Start()
    int player_life = MyObject.GetComponent<Script_A>().currentHealth;

Now you get a component that’s on the gameobject that you just assigned in the editor, and not on your own gameobject.

Show more replies
  • Liked by
1 on February 5, 2016

Thank you all!!

on February 6, 2016

No problem man. Glad I could help! These guys have helped me out with certain things, even though I could figure them out on my own, it’s good to ask. Discussing things with code help you understand it even with very simple answers or questions of others. Like a previous post, I said I didn’t have my rubber ducky to speak too. It’s just a saying. It helps a lot just to type it out and really get a feel of what you’re asking, it normally will also help you figure it out on your own.

Show more replies
  • Liked by