How to dynamically access scripts from other gameobjects?

So here’s what I plan on building in Unity:
I will be creating a 2D simulation of several logic gates, LEDs, buttons and such. All these components will be prefabs, so the user can choose which and how many to load. The components can be linked by connecting them using “wires” that transmit the current from one component to the other.

My idea was to add a script with a static variable “current” to every gameobject and have other gameobjects read the variable from that script in order to retrieve the current emitted from the connected gameobject.
The real problem is that I can’t get Unity to dynamically assign a script to a variable. So my question is: Is this possible, or might there be a better solution?

I’m not sure you want to use a static variable. If a variable is static, all game objects which use the class/script “share” the value of the static variable. Wouldn’t you want each game object to have it’s own value for current?

To access a variable in a script attached to another game object, you first need a reference to that GameObject. One way would be to do this on collision, another is using GameObject.FindWithTag. How you do it depends on your design.

You then need a reference to the component (script) which has the variable you want. Do this with GetComponent.

You can then access any public variables and methods in that component using dot notation.

Here’s a C# example which checks another electric object’s current on a collision. Assume objects with the tag “Electric Object” have an the ElectricCharge script attached.

public class ElectricCharge : MonoBehaviour {
    public int current = 0;

    void OnCollisionEnter(Collision collision) {
        if (collision.gameObject.tag == "Electric Object") {
            int otherObjectCurrent = collision.gameObject.GetComponent<ElectricCharge>().current;
            Debug.Log("The other object's current is: " + otherObjectCurrent);
        }
    }
}