Accesing a variable in another script. C#

First, i want to say that i have been googling, and searching on this site,
but never found a clear answer or found something that worked.

Here we go:

We have a gameobject called A
This object A got a C# script called ScriptA
In this ScriptA we have a int called ScriptAInt

We also have a gameobject called B
This object A got a C# script called ScriptB
In this ScriptB we have a int called ScriptBInt

I want to be able to make ScriptBInt be the same as ScriptAInt

By looking at the scripting rererence, ive come to this.

for ScriptA:

public int ScrptAInt = 5;
void update()
{
ScriptB B;
B = B.GetComponent(“ScriptB”) as ScriptB;
B.ScriptBInt = ScriptAInt;
}

But this doenst work for me.

How would you do this, and why?

I copied your title “Accesing a variable in another script. C#”, pasted it on google and found

Enjoy:)

The problem is: you may have several instances of ObjectA and ObjectB in your scene, thus you must have a reference to the target object to get its script. And what’s a reference? In Unity, any object component is a reference: GameObject, Transform, Collider, Rigidbody etc (but GameObject and Transform are more popular, because any game object has both).

You can drag the object to the reference variable in the Inspector, or you can find the object with Find, FindWithTag etc., or you can get its collider when colliding with it, etc.

Using a reference, your code would become:

public int ScrptAInt = 5;
public Transform objB; // <- drag object B here (objB is the reference)

void Update()
{
  ScriptB B = objB.GetComponent< ScriptB>(); // the generic version doesn't need typecasting
  B.ScriptBInt = ScriptAInt;
}