- Home /
Null Reference Exception Issue with GetComponent()
I've been trying to get getcomponent to work with getting an enemyobject to take a variable from another script on an empty object titled GameController. The enemy object is a prefab while the GameController is not. I'm getting the Null Reference Exception problem when trying to get the speed variable from the gamecontroller and I don't know what the problem is.
Here is the enemybehavior script:
private var newEnemySpeed:GameController;
private var enemySpeed: float;
function Start () {
newEnemySpeed.GetComponent(GameController);
enemySpeed= newEnemySpeed.enemySpeed;
}
function Update () {
Move(enemySpeed);
}
function Move(a:float)
{
transform.Translate(Vector3.left * a * Time.deltaTime);
if (transform.position.x <= -12)
{
Destroy(gameObject);
}
}
on the GameController object is a variable: enemySpeed that will increase in value every second.
GetComponent
usually works on a GameObject
, so I'd expect your newEnemySpeed
to be a GameObject
. How does this variable get initialised? In your code it's never given a value.
I don't think it's getting initialized anywhere else as it's set to a private variable so it's not showing up on the inspector.
Answer by meat5000 · Aug 19, 2013 at 07:54 PM
I think this line doesnt do anything :
newEnemySpeed.GetComponent(GameController);
I could be wrong :/ but you probably need to make it equal something
newEnemySpeed = GameController.GetComponent(GameController);
which is :
newEnemySpeed{script] = GameController[GameObject].GetComponent(GameController[Script]);
I was following the logic from the tutorial on getcomponent and I thought that one script can access the variables of a script via getcomponent.
Your answer
![](https://koobas.hobune.stream/wayback/20220613112536im_/https://answers.unity.com/themes/thub/images/avi.jpg)