- Home /
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".
You have to assign a gameobject or a prefab to the LevelScroller in the inspector.
I placed the LevelScroller object which has the $$anonymous$$oveRight script onto an "enemy" object which has the SurfaceDeathScript. It ends up removing itself upon runtime though. I've removed the "public GameObject LevelScroller;" line though as I don't think it was needed.
Answer by tswalk · Jun 29, 2014 at 05:23 AM
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: http://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
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)
Nothing wrong with creating a variable of the class type reference to the component. Its far better to do it this way then to call getComponent every time you want it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613152756im_/https://answers.unity.com/themes/thub/images/avi.jpg)