variables cross-scripts, need some robust syntax

well i’m constantly stumbling around in this sector, so i might as well get the record set straight so i can focus on how my scripts are interacting and not on how one script isnt seeing another.

anyway, i’m kindly requesting that you guys just type up a single line or so for each of the following two scenarios, assuming 3 things

  1. the name of object A (as in, the physical entity within unity to which the object is attached) is OBJ_A, and object b is OBJ_B
  2. the name of the scripts attached to object a and b are JSC_A and JSC_B respectively
  3. the name of the variables in the scripts a and b are VAR_A and VAR_B respectively

ok, now for the cases;

CASE 1: accessing VAR_A that resides within JSC_A on OBJ_A, with a script being executed from OBJ_B

CASE 2: accessing VAR_A from a within OBJ_A, but a script separate from where VAR_A is

oh and go crazy with how you do it, either by using that object.lookfor thing or simply defining a game object beforehand, whatever YOU think is better.

var OBJ_B = GameObject.Find("OBJ_B"); <- find the gameobject in the scene.
you could also assing a tag and use FindWithTag.
OBJ_B.GetComponent(JSC_A).VAR_A = MyNewVar_A; <- assign the new var.

GetComponent(JSC_A).VAR_A = MyNewVar_A;

if you look in the script reference you can deduct how its done.

looks different, but does the same:

//gets varXYZ in  JSC_A which is attached to OBJ_B
var OBJ_B = GameObject.Find("OBJ_B");
var objconnect = OBJ_B.GetComponent("JSC_A");
//.........
if(objconnect.varXYZ){
    doSomething();
}
// i like this version more because i always know which variable comes from

Sweet! thanks guys.
anykey’s version seems like it would be more simplistic and maybe a little faster as long as the number of objects being referenced to are small, since it isn’t running a .Find every frame.

If you want robust syntax, you should use generics:

var objconnect : JSC_A = OBJ_B.GetComponent.<JSC_A>();
objconnect.varXYZ;

This is compile-time type-safe and requires no reflection or casting of types.

The whole issue of calling Find once and storing the reference for later use is good practice in general (and this likely will be the single largest factor to fast code)