Access another script in another GameObject in C#

I have two objects A and B, each of them has a C# script A1 and B1. Now I am in script A1 and want to access a public variable in B1. I tried GetComponent() as what I did successfully in JavaScript but it didn’t work in C#.

I found this topic in the forum:
http://forum.unity3d.com/viewtopic.php?t=9964

I tried the way it suggested as:
(in script A1)

public class A1: MonoBehaviour{

//I dragged B here in the editor
public GameObject B;

void Update()
{
transform.Rotate(Vector3.up, (B1)B.GetComponent(typeof(B1)).someVariable);

}

And an error appeared in the debugger:
The type or namespace name `B1’ could not be found. Are you missing a using directive or an assembly reference?

Thanks in advance.

I normally do something like this:

public class A1 : MonoBehaviour {
    
    public GameObject B;
    private B1 b1Script;

	// Use this for initialization
	void Start () {
        // Cache the script so it's not looked for during update
	    b1Script = B.GetComponent("b1Script") as b1Script;
	}
	
	// Update is called once per frame
	void Update () {
	    
// you can now use the variable by
b1Script.nameofvariable
}

The variables have to be public to be accessed i think or have a public getter.

Hope the above helps and i didn’t mix up all the A’s and B’s

Regards,
Matt.

I tried your suggestion unfortunately it does not work.

b1Script = B.GetComponent("b1Script") as b1Script;

Shouldn’t this sentence be:

b1Script = B.GetComponent("B1") as B1

because “B1” is the class name of the script?

Also I always get cannot find “B1” definition. Should I include the script class like “using MonoBehaviour.B1;” or in some other way?

At last I made a compromise and worked it out. I used a JavaScript that can talk both to these two C# scripts as a communicator. Not a efficient way but works temporarily. :slight_smile:

Yeah it should be… all those A’s and B’s and B1’s. My code was off the top of my head and not tested.

You should be able to see the b1Script within the scope of the A1 class.