- Home /
Better way of interacting and sharing variable between two scripts?
When I make a share of variable between two object (such as finding the player in playerJump script when the player is instantiated), I usually use Find.findgameobjectwithtag() method. By using this way all the times, it sometimes make things complicated. need to make exception for the object not exist, Find method takes too much system resources etc... so I thought there might be a better way that I do not know. is there any way to handle this issue?
Answer by xibanya · Dec 24, 2019 at 03:12 AM
Will there only ever be one player at a time? If so, at the top of your player class you could put
public static Player instance;
and then in Awake()
if (instance == null) instance = this;
let's say you're looking for player health. In the Player class you could have something like,
public static bool TryGetHealth(out float health)
{
health = instance?.health ?? 0;
return instance != null;
}
usage in another script would be
if (Player.TryGetHealth(out float playerHealth))
{
//do something with player health
}
else
{
//handle not being able to find the player this way (maybe now do the find by tag as a last ditch attempt)
}
If you may have more than one player at a time, you will want to take another approach. One would be to give each player a unique ID and use a static Dictionary instead. You would need to add using System.Collections.Generic;
to the top of the Player class file, then inside the class put public static Dictionary<int, Player> players = new Dictionary<int, Player>();
put public int id;
in your variable declarations and manually assign it in the inspector OR add private static int playerCount;
inside the class and increment it for each player created, then assign playerCount as the id.
In Start() put
if (!players.ContainsKey(id)) players.Add(id, this);
and in OnDestroy() put
if (players.ContainsKey(id)) players.Remove(id, this);
TryGetHealth would then look like this
public static bool TryGetHealth(int id, out float health)
{
bool exists = players.ContainsKey(id);
health = exists? players[id].health : 0;
return exists;
}
I didn't even know that i could get the value with 'out' thing. ! Awesome!! thanks.
Yep, it's pretty handy! Here's the official microsoft docs on it: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier
ref
is a similar and also very handy keyword for getting values out of a method without that necessarily being the return value https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref