- Home /
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'm confused. Why don't you just do what the error indicates you should do:
var other : Player$$anonymous$$ovement;
other = gameObject.GetComponent(Player$$anonymous$$ovement);
Typically I place the second line in Start().
It's part of the language, you can't initialize a variable when it depends on other variables of the same class. Unity will assign the gameObject
variable after the construction of the object, however when assigning a variable in the declaration, it will try to do it before the object is created, so you can only use static data for initalization.
The answer is to do what the error message says as @robertu suggested.
Answer by slayer29179 · Nov 19, 2013 at 09:18 PM
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()
{
}
thanks for the quick response! I actually found out how to!
var other : ScriptName;
this works perfectly! thanks again! EDIT: thanks robertbu
Answer by iwaldrop · Nov 19, 2013 at 09:24 PM
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);
}