- Home /
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?
Answer by hamstar · Nov 21, 2013 at 05:28 PM
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);
}
}
}
I just re-read your question and I'm not sure if this is what you were asking. I can delete this if it's not helpful.
$$anonymous$$y approach was exactly the same. The only reason my script threw an error turned out to be a syntax error. The project now finally compiles and it seems to run just fine. Thank you so much for helping me out! Problem solved.
Your answer
Follow this Question
Related Questions
Script loads font, how do I change the color? 2 Answers
What's the best way to store a reference to a script asset? 2 Answers
How to parent a GUI text to current game object 3 Answers
Which is better: script or animation (which needs to change with scripting)? 1 Answer
Is it possible to compile and run C# code on-the-fly on mobile? 1 Answer