Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass variable from one script to another C# Unity 2D?

For example I have a variable (public static float currentLife) in script "HealthBarGUI1" and I want to use this variable in another script. How do I pass variable from one script to another C# Unity 2D?

like image 599
MickyD47 Avatar asked Apr 08 '14 04:04

MickyD47


People also ask

How do I pass a variable from one script to another in JavaScript?

In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting.


1 Answers

You could do something like this, because currentLife is more related to the player than to the gui:

class Player {

  private int currentLife = 100;

  public int CurrentLife {
    get { return currentLife; }
    set { currentLife = value; }
  }

}

And your HealthBar could access the currentLife in two ways.

1) Use a public variable from type GameObject where you just drag'n'drop your Player from the Hierarchy into the new field on your script component in the inspector.

class HealthBarGUI1 {

  public GameObject player;
  private Player playerScript;

  void Start() {
    playerScript = (Player)player.GetComponent(typeof(Player)); 
    Debug.Log(playerscript.CurrentLife);
  }

}

2) The automatic way is achieved through the use of find. It's a little slower but if not used too often, it's okay.

class HealthBarGUI1 {

  private Player player;

  void Start() {
    player = (Player)GameObject.Find("NameOfYourPlayerObject").GetComponent(typeof(Player));
    Debug.Log(player.CurrentLife);
  }

}

I wouldn't make the currentLife variable of your player or any other creature static. That would mean, that all instances of such an object share the same currentLife. But I guess they all have their own life value, right?

In object orientation most variables should be private, for security and simplicity reasons. They can then be made accessible trough the use of getter and setter methods.

What I meant by the top sentence, is that you also would like to group things in oop in a very natural way. The player has a life value? Write into the player class! Afterwards you can make the value accessible for other objects.

Sources:

https://www.youtube.com/watch?v=46ZjAwBF2T8 http://docs.unity3d.com/Documentation/ScriptReference/GameObject.Find.html http://docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html

like image 119
Wipster Avatar answered Sep 19 '22 19:09

Wipster