How do I access a variable from another script in the same object and also another, similar object.

I have two objects and two scripts. Both objects have both scripts, and each variable is different based on some factors. This is the basic code I have so far:

public class Par : MonoBehaviour
	float magStr;  
	public static Par instance;
	void Awake
		instance = this;

public class Mag : MonoBehaviour
	void Start
		var magStr = //something that gives value of the variable from Par for this object  
		var tarMagStr = //something that gives the value of the variable from Par for the other object


in Mag you do

Par myParInstance = GetComponent<Par>();

then you access your variable like this:


for the other object’s Par you can do in many ways:

  • you can keep property referencing to it;
  • you can do a GameObject.FindByName/Tag/Id and save it into a variable;

Honestly it depends on your design the way you should approach it.

A simple example is having

Par otherGameObjectPar = GameObject.Find("otherObjName").GetComponent<Par>();
// to get
// otherGameObjectPar.yourVariableName value

Answer by wideeyenow_unity

I too am fighting with getting variables, but it’s recommend to cache if you can(research caching). But so far the only real way to do it is:

 GameObject objB;
 void Start()
     objB = GetComponent<ScriptB>().gameObject;

or something very similar to that. But GetComponent() will be your best friend, and later on your worst enemy, lol

This was posted on a duplicate question.