Communicating between Scripts in Unity
In developing games most of the C# scripts will generally be linked to GameObject.You may sometimes need these scripts to communicate with each other.
Let’s consider two game objects gobj1 and gobj2 and two script1 && script2
Let’s create Script2 and attach it to gobj2.
Let’s code Script2 as follows
Let’s code Script1 as follows
Here first need to find out where is Script2.
Script2 is attached to the second gObj2 , so let’s find out the GameObject from the panel.
GameObject.Find(“gObj2”)
This script will find the game object. Each gameobject will have a component attached to it. Here Script2 is also a component for the gameObject gobj2. hence we can access like
GameObject.Find(“gObj2”).GetComponent<Script2>();
So when the script2 is accessed we can access their public methods throug dot notations.
script2.fname()