Getting member values from other scripts

Hi community,
I am very new to both unity and scripting, so this might be a very simple error I am making.
So, the following is happening. I have two different scripts, and I want to access member variables from one by the other. I can’t make them static, and am currently trying around with the “GetComponent”, but I have yet to fully understand what a component actually is, and have a number of compile errors I don’t understand.
Am I doing something basic wrong? And what, really, is a component in the Scene?

A component is basically everything you add to a game object. If you attach a script to a game object, its a component. If you add a mesh renderer, its a component etc. You can only use GetComponent if you have a component attached to the game object. So let’s say you want to access another script (component) on the same game object, you can use GetComponent() to access the script and its properties.

So that would mean, that it is impossible to access a component without having a gameObject, right? So, if I want script A to have a look at script B’s members, script A needs vision on a gameObject which has script B as a component?

I’m not saying it’s impossible, but in most cases you add a script to a game object and you get acces to it with GetComponent because the script is a component of the game object. I believe you can get access to a script within your project hierarchy (without attaching to gameobject) but I haven’t tried that myself yet.

Yes, you need the gameobject to find the component. There are possible ways around this, but it’s best to avoid them.

Thank you very much, now I know what to do =)

Just in case anyone is still seeing this, I am getting an error at one point. I think it’s best if I just paste the code somewhat:

void OnCollisionEnter(Collision col){
GameObject ball = col.collider.gameObject;
Vector3 newDir = (Vector3)(ball.GetComponent(BallMove).currentMoveDir);
// Stuff
}

it is where I set newDir to be currentMoveDir, a Vector which is a public member in the BallMove script. When I hover over it, mono says “unresovled member”, so I guess there is the problem. The cast didn’t do anything. The error is

"unity cs0119 expression denotes a type' where a variable' value' or method group' was expected"

Try this:

Vector3 newDir = (Vector3)((ball.GetComponent(typeof(BallMove)) as BallMove).currentMoveDir);

Also assuming that currentMoveDir is of the Vector3 type then you don’t need the last cast:

    Vector3 newDir = (ball.GetComponent(typeof(BallMove)) as BallMove).currentMoveDir;

Thank you, everything is working perfectly now.

Why not use the Generic version?

 Vector3 newDir = ball.GetComponent<BallMove>().currentMoveDir;

So much neater.