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

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

+5
source share
3 answers

You can do something like this because currentLife is more associated with the player than with gui:

class Player {

  private int currentLife = 100;

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

}

And your HealthBar can access currentLife in two ways.

1) Use a public variable from the GameObject type, where you simply drag and drop your Player from the hierarchy into the new field of 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) find. , , .

class HealthBarGUI1 {

  private Player player;

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

}

currentLife . , currentLife. , , ?

, . .

, , oop . ? ! .

:

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

+9

:

HealthBarGUI1.currentLife

, HealthBarGUI1 - MonoBehaviour script.

, 2 GameObject, - :

gameObject.GetComponent<HealthBarGUI1>().varname;
0
//Drag your object that includes the HealthBarGUI1 script to yourSceondObject place in the inspector.

public GameObject yourSecondObject;

class yourScript{

    //Declare your var and set it to your var from the second script.
    float Name = yourSecondObject.GetComponent<HealthBarGUI1>().currentLife;

}
0
source

Source: https://habr.com/ru/post/1535471/


All Articles