x


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;
}
more ▼

asked Apr 29 '12 at 04:39 PM

Hedonsoft gravatar image

Hedonsoft
54 12 25 30

Why aren't you using 'col.gameObject' instead 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.

Apr 29 '12 at 04:43 PM syclamoth

Ahh good to know thanks. I had seen the .Find() technique used in a tutorial. Will use the other method from now on.

Apr 29 '12 at 04:54 PM Hedonsoft

Much appreciated with the tips guys, solved my health script problem. Thanks again!

May 07 '12 at 12:16 AM NorthernEagle
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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();
more ▼

answered Apr 29 '12 at 04:49 PM

Henrique Vilela gravatar image

Henrique Vilela
318 11 14 19

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x405
x396
x207

asked: Apr 29 '12 at 04:39 PM

Seen: 854 times

Last Updated: May 07 '12 at 12:16 AM