Another way to reference scripts?

Hi, I am trying to find another way to reference a script so that another script can use its info(variables, etc)

I have been using a way that has been successful, but produces annoying error.

Here is the code

var other = gameObject.GetComponent(PlayerMovement);

like I said it works, but produces an error such as this

“UnityException: You are not allowed to call this function when declaring a variable.
Move it to the line after without a variable declaration.
If you are using C# don’t use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function.
UnityEngine.Component.get_gameObject () (at C:/BuildAgent/work/cac08d8a5e25d4cb/Runtime/ExportGenerated/Editor/UnityEngineComponent.cs:183)
NoMovement…ctor () (at Assets/Scripts/NoMovement.js:5)”

Normally this wouldnt bother me much, but these errors are starting to build up

Any help would be greatly appreciated! Let me know if you need additional info!

I assume you are setting your script up as such:

#pragma strict
var other = gameObject.GetComponent(PlayerMovement);

function Update()
{

}

Yes? Set it to this instead and it will work:
#pragma strict
var other : PlayerMovement;

    function Start()
    {
     other = gameObject.GetComponent(PlayerMovement)
    }
  
    function Update()
    {
    
    }

You can’t dynamically assign member variables in the class definition; you have to do this another way. There are two common approaches.

  1. Drag the script that you want to reference to the inspector. This is the easiest.

  2. Do the GetComponent call in Awake or Start.

    var other : PlayerMovement;

    function Awake()
    {
    other = GetComponent(PlayerMovement);
    }