- Home /
GetComponent usage returns NullReferenceException, not sure why
Hi everyone. I have a powerup in my game called crate. When the player collides with it I'm trying to run a function called MachineGun() in my FireScript that increases the bullet fireFreq. When my player collides with the powerup I'm getting a NullReferenceException and I don't know why.
 GameController.js
 function OnTriggerEnter(col:Collider){
             if(col.gameObject.tag == "Player" && canPickup){
             canPickup = false;
                 GameObject.Find("PlayerPrefab").GetComponent(FireScript).MachineGun(); //error occurs here. My player is called PlayerPrefab, the FireScript is attached to the prefab, and the script contains a MachineGun() 
                 var cloneCrateSound = Instantiate(crateCollectionSnd, transform.position, transform.rotation);
                 var cloneArmsCollected = Instantiate(armsCollected, transform.position, Quaternion.Euler(Vector3(0,180,0)));
                 
                 renderer.enabled = false;
                 yield WaitForSeconds(2);
                 Destroy(cloneCrateSound);
                 Destroy(cloneArmsCollected);
                 Destroy(gameObject);
             ...
             }
In FireScript.js
 function MachineGun(){
     gunType = 1;
     bulletTimer = 10;
 }
Why aren't you using 'col.gameObject' ins$$anonymous$$d of GameObject.Find? In general, you should avoid using GameObject.Find wherever you possibly can- and I'm not convinced that you need to use it here, either.
Ahh good to know thanks. I had seen the .Find() technique used in a tutorial. Will use the other method from now on.
$$anonymous$$uch appreciated with the tips guys, solved my health script problem. Thanks again!
Answer by Henrique Vilela · Apr 29, 2012 at 04:49 PM
Try to split your problematic line in 3. That way you can at least identify where the error really are.
Like:
 GameObject player = GameObject.Find("PlayerPrefab");
 MonoBehavior fire = player.GetComponent(FireScript);
 fire.MachineGun();
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                