Accessing Scripts from a different Script

So I’ve been trying to alter the contents of my “MoveRight” script from my “SurfaceDeathScript”, specifically I want to alter the value of a variable, and I know I’m supposed to use the “GetComponent” thing to accomplish this. I’ve looked up several sources, but for some reason I can’t seem to get it right. I’m using C# btw.

public class SurfaceDeathScript : MonoBehaviour 
{
 
	public MoveRight moveRightScript;

	void Start ()
	{
		moveRightScript = gameObject.GetComponent<MoveRight>();

I’ve tried this, but I get “the name MoveRight does not exist in the current context”. I’ve also tried a whole manner of different ways, but to no avail. Any help would be appreciated, thank you.

EDIT:

Actually, I managed to write this and it worked:

public class SurfaceDeathScript : MonoBehaviour 
{
    public GameObject LevelScroller;
    public MoveRight moveRightScript;
 
    void Start ()
    {
        moveRightScript = LevelScroller.GetComponent<MoveRight>();
    }
 
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Player")
        {
            moveRightScript.levelscrollSpeed = 0.04f;
        }
    }
}

In unity I dragged the LevelScroller object into both the LevelScroller and MoveRightScript boxes, as it contains the MoveRight script, while this does work, I get an error at the start that says “UnassignedReferenceException: the variable LevelScroller of SurfaceDeathScript has not been assigned”.

Like the error says… you haven’t actually assigned it anything as you have only created the variable to hold the reference, but not given it anything to reference (if that makes sense).

If all of these scripts are on the same object… you were close in your first example as you “referenced” the “gameobject” to get its’ component MoveRight.

see the example in the docs: Unity - Scripting API: GameObject.GetComponent

create the variable to hold the reference (in that case a public, so you can drag your object onto the variable in the inspector).

“get” the component (script) on that reference (which is basically itself in this example).

assign the value to that references variable.

and btw, you don’t create a variable reference of the “class” you will use (moveright), you will create a reference for a GameObject (the object with the component you want)