Hi there, I am making a game in which lots of different scripts on the same game object will reference each other frequently. So I am wondering what the best way to do this is for performance.
So first off, is referencing a variable from another script using:
variable = GetComponent<OtherScript> ().otherVariable;
any slower than referencing a variable from the same script, ie:
variable = otherVariable;
Secondly, though I guess the first question will answer this one… If I am using a variable from another script multiple times in each update/fixedupdate, would I be better off constantly referencing the variable from the other script, or would I be better off saving the variable as a variable within the same script first, and then referencing that? For example, which would be quicker:
this…
void FixedUpdate () {
LookForFood ();
}
void LookForFood () {
if (GetComponent<AI> ().targetSearch == Vector3.zero || Vector3.Distance (transform.position, GetComponent<AI> ().targetSearch) < GetComponent<AI> ().searchDistance)
NewSearchTarget ();
}
void NewSearchTarget () {
GetComponent<AI> ().targetSearch.x = transform.position.x + Random.Range (-GetComponent<AI> ().searchRange, GetComponent<AI> ().searchRange);
GetComponent<AI> ().targetSearch.y = transform.position.y + Random.Range (-GetComponent<AI> ().searchRange, GetComponent<AI> ().searchRange);
}
or this…
void FixedUpdate () {
search = GetComponent<AI> ().targetSearch;
distance = GetComponent<AI> ().searchDistance;
range = GetComponent<AI> ().searchRange;
LookForFood ();
}
void LookForFood () {
if (search == Vector3.zero || Vector3.Distance (transform.position, search) < distance)
NewSearchTarget ();
}
void NewSearchTarget () {
search.x = transform.position.x + Random.Range (-range, range);
search.y = transform.position.y + Random.Range (-range, range);
}
I know the latter is easier to read, but in this case it wouldn’t matter too much because this script and similar ones are going to be about this short.