- Home /
Communication between classes from two different game objects
Hey, my problem may seem a basic one, but after some research I could not find a proper answer on this matter. My issue is the following: I have two different game objects in the scene with two different scripts attached to each other; I want to change a variable from one script using the other script and I tried to use some basic C# knowledge which MonoBehaviour seemed to reject. By this I mean that I tried to make like a ,,key" which should enable me the communication between scripts. Still MonoBehaviour asks me to use AddComponent and rejects the way I wrote the script.
Making no bone, could someone give a simple example of a script which should solve the aforementioned problem?
Answer by juicyz · Aug 26, 2016 at 04:47 AM
1 GameObject called FirstObject with the OneObject.cs script on it.
1 GameObject called SecondObject with the TwoObject.cs script on it.
public class OneObject : MonoBehaviour {
public int number = 0;
TwoObject obj;
void Start() {
obj = GameObject.Find("SecondObject").GetComponent<TwoObject>();
obj.otherNumber = 10;
}
}
public class TwoObject : MonoBehaviour {
public int otherNumber = 1;
}
Instead of using GameObject.Find you can use the following also: - FindGameObjectsWithTag - FindWithTag https://docs.unity3d.com/ScriptReference/GameObject.html
OR you can provide the SecondObject to the FirstObject using the Drag and Drop features of the GUI and not have to use the Find methods. Still need the GetComponent call to get the script though and a public GameObject for it.
Your answer
Follow this Question
Related Questions
How do I access a script from a class inside a script. 1 Answer
How do I save an array of all different variables? 0 Answers
Using a variable value with GetComponent 1 Answer
Variables having 2 values within a Class? 0 Answers
How do I access a script variable from a class defined within that script? 1 Answer