Here’s is how i usually access the other GameObjects:
First Method:
Declare the GameObject as public for example
public GameObject myobject;
Then drag the GameObject we want to access to myobject in the inspector.
You can also directly access the particular component of the gameobject as that would be more effecient.
For Example:
public Transform transform;
Then you can just drag the gameobject to transform in the inspector and you can access the Transform Component of the dragged gameobject.
Second Method:
You can use
GameObject.Find("Gameobjectnamehere");
or
Gameobject.FindGameObjectWithTag("");
This is ofcourse less effecient than the first method described above.
For getting a Component of any particular gameobject you can use the following
Simple Example Here:
public GameObject otherobject;
Transform otherobjecttransform=otherobject.transform;
You can also use this:
//Ignore the space below in angular brackets as thats how this site is designed..
Transform otherobjecttransform=GameObject.Find("otherobject").GetComponent
< Transform >();
This above code line will Find the GameObject name otherobject and get it’s TransForm Component
Public Static Variables
You can Create A public Static Variables in the Script so that they can accessed in other Script
Here is the simple example:
public static int score;
Just for understanding assume that this variable is in Script called global.cs. Now you can easily access this variable anywhere(in any script) using
global.score;
int getscore=global.score;
Not only that you can also create public static methods in C# script.
For Example:
public static void printmyname()
{
Debug.Log("MyName");
}
Now assuming that this method is in script called global.cs you can access it anywhere just by calling this method as belows:
global.printmyname();
Do note that a static method must contain static variables.
Check this page Accessing Other GameObjects in Refrence Doc for detailed explanation as well as sample code. Ofcourse select C# instead of JavaScript for code and also do check this Accessing other Components .
Please if anybody who knows more please comment on this if i have made some mistake as well as make suggestions and suggest new ways