• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
-1
Question by Zummatul · Jan 19, 2013 at 05:23 PM · nullreferenceexception

NullReferenceException: Object reference not set to an instance of an object

I got some unity3d files and trying to set it up on my game(just for fun) I am making it alone(just started it) I have been getting this error in 5 scripts(I didnt made)(got it while surfing the net) NullReferenceException: Object reference not set to an instance of an object Any help would be really appreciated Here are the scripts:

ERRORS:NullReferenceException: Object reference not set to an instance of an object SwitchWeapons.HideWeapons () (at Assets/Scripts/Player/SwitchWeapons.js:62) UnityEngine.Component:BroadcastMessage(String) PlayerWeapons:SelectCurrentWeapon(Int32) (at Assets/Scripts/Player/PlayerWeapons.js:95) PlayerWeapons:Start() (at Assets/Scripts/Player/PlayerWeapons.js:15)

' @script AddComponentMenu("Shooter Engine/Player/Switch Weapons")

 var primaryWeapon : GameObject;
 var primaryIndex : int = 0;
 var secondaryWeapon : GameObject;
 var secondaryIndex : int = 0;
 
 private var player : FPSPlayer;
 private var primary : boolean = true;
 
 function Start () {
     player = transform.root.GetComponentInChildren(FPSPlayer);
 }
 
 function Update () {
     if (primaryWeapon == null || secondaryWeapon == null || !player.hasWeapon[primaryIndex] || !player.hasWeapon[secondaryIndex])
         return;
         
     if (Input.GetButtonDown("SwitchWeapon") && (player.currentWeapon == primaryIndex || player.currentWeapon == secondaryIndex)) {
         if (primary)
             SelectSecondary();
         else
             SelectPrimary();
     }
 }
 
 function SwitchWeapon () {
     if (primaryWeapon != null && player.hasWeapon[primaryIndex] && player.currentWeapon != primaryIndex)
         SelectPrimary();
     else if (secondaryWeapon != null && player.hasWeapon[secondaryIndex] && player.currentWeapon != secondaryIndex)
         SelectSecondary();
 }
 
 function SwitchCurrentWeapon () {
     if (primaryWeapon != null && player.hasWeapon[primaryIndex] && player.currentWeapon == primaryIndex)
         SelectPrimary();
     else if (secondaryWeapon != null && player.hasWeapon[secondaryIndex] && player.currentWeapon == secondaryIndex)
         SelectSecondary();
 }
 
 function SelectPrimary () {
         if (secondaryWeapon != null)
             secondaryWeapon.SetActiveRecursively(false);
         primaryWeapon.SetActiveRecursively(true);
         player.currentWeapon = primaryIndex;
         if (Time.timeSinceLevelLoad > 0.1)
             transform.root.BroadcastMessage("WeaponChanged", SendMessageOptions.DontRequireReceiver);
         primary = true;
 }
 
 function SelectSecondary () {
         if (primaryWeapon != null)
             primaryWeapon.SetActiveRecursively(false);
         secondaryWeapon.SetActiveRecursively(true);
         player.currentWeapon = secondaryIndex;
         if (Time.timeSinceLevelLoad > 0.1)
             transform.root.BroadcastMessage("WeaponChanged", SendMessageOptions.DontRequireReceiver);
         primary = false;
 }
 
 function HideWeapons () {
     if (primaryWeapon != null && player.currentWeapon != primaryIndex)
         primaryWeapon.SetActiveRecursively(true);
     if (secondaryWeapon != null && player.currentWeapon != secondaryIndex)
         secondaryWeapon.SetActiveRecursively(true);
 }

ERROR:NullReferenceException: Object reference not set to an instance of an object FPSAnimation.Start () (at Assets/Scripts/Player/FPSAnimation.js:89)

 @script AddComponentMenu("Shooter Engine/Player/FPS Animation")
 
 var crouchMultiplier : float = 0.9;
 var walkMultiplier : float = 0.7;
 var defaultIsWalk : boolean = true;
 var aimTime : float = 0.0;
 var animatedMesh : Animation;
 var standAnims : AnimationClip[] = new AnimationClip[1];
 var standAimAnims : AnimationClip[] = new AnimationClip[1];
 var standShootAnims : AnimationClip[] = new AnimationClip[1];
 var standAnimsSpeed : float = 1.0;
 var walkAnims : AnimationClip[] = new AnimationClip[1];
 var walkAimAnims : AnimationClip[] = new AnimationClip[1];
 var walkShootAnims : AnimationClip[] = new AnimationClip[1];
 var walkAnimsSpeed : float = 1.0;
 var walkHeadBobMultiplier : float = 1.0;
 var runAnims : AnimationClip[] = new AnimationClip[1];
 var runAimAnims : AnimationClip[] = new AnimationClip[1];
 var runShootAnims : AnimationClip[] = new AnimationClip[1];
 var runAnimsSpeed : float = 1.0;
 var runHeadBobMultiplier : float = 1.0;
 var reloadAnims : AnimationClip[] = new AnimationClip[1];
 var changeWeaponAnim : AnimationClip;
 var setTimeForChange : boolean = false;
 var timeForChangeWeapon : float = 0.3;
 var jumpingAnimation : AnimationClip;
 var jumpingSound : AudioClip;
 var fallTimeThreshold : float = 0.2;
 var fallingDamage : boolean = true;
 var injuredTimeThreshold : float = 1.0;
 var deadTimeThreshold : float = 2.0;
 var idleAnimations : AnimationClip[];
 var idleSounds : AudioClip[];
 var alwaysSnapHandToWeapon : boolean = false;    //allows use the same animation set for the different weapons
 var includingJump : boolean = true;    //snap a left hand to the weapon when player jumps
 var includingIdle : boolean = true;    //snap a left hand to the weapon while idle
 var leftFoot : Transform;    //left foot gameObject of your character
 var rightFoot : Transform;    //right foot gameObject of your character
 var playerObject : Transform;
 var crouchedPlayerObjectY : float = 0.0;
 var crouchedColliderHeight : float = 1.0;
 var crouchedColliderCenterY : float = -0.5;
 @HideInInspector var grounded : boolean = true;
 @HideInInspector var aim : boolean = false;
 @HideInInspector var shoot : boolean = false;
 @HideInInspector var gunIsEmpty : boolean = false;
 @HideInInspector var playerObjectPos : float;
 
 static var busy : boolean = false;
 
 private var rb : Rigidbody;
 private var c : FPSController;
 private var cam : FPSCamera;
 private var player : FPSPlayer;
 private var crosshair : FadeGUITexture;
 private var aimWeapons : AimWeapons[];
 private var crouch : boolean = false;
 private var run : boolean = false;
 private var doJumping : boolean = false;
 private var doWaiting : boolean = false;
 private var fallingTimer : float = 0.0;
 private var idleTimer : float = 0.0;
 private var jumpSound : boolean = false;
 private var jump : boolean = false;
 private var superJump : boolean = false;
 private var injured : boolean = false;
 private var dead : boolean = false;
 private var waiting : boolean = false;
 private var currColliderHeight : float;
 private var currColliderCenterY : float;
 private var currPlayerObjectY : float;
 private var playerObjectVelocity : float = 0.0;
 private var curGroundSpeed : float;
 private var curHeadBobDist : Vector2;
 private var lastFireTime : float = 0.0;
 private var pauseFilterEffect : String;
 private var footstepTime : float;
 private var footstepTimer : float = 0.0;
 private var swapFoot : boolean = false;
 private var vol : float;
 
 function Start () {
     rb = rigidbody;
     c = GetComponent(FPSController);
     cam = Camera.main.GetComponent(FPSCamera);
     player = GetComponent(FPSPlayer);
     crosshair = player.crosshairGUI.gameObject.GetComponent(FadeGUITexture);
     aimWeapons = FindObjectsOfType(AimWeapons) as AimWeapons[];
     pauseFilterEffect = FindObjectOfType(PauseMenu).pauseFilterEffect;
     if (animatedMesh == null || !animatedMesh.gameObject.active)
         animatedMesh = gameObject.GetComponentInChildren(Animation);
     currColliderHeight = collider.height;
     currColliderCenterY = collider.center.y;
     currPlayerObjectY = playerObject.localPosition.y;
     playerObjectPos = currPlayerObjectY;
     curGroundSpeed = c.groundSpeed;
     curHeadBobDist = cam.headBobDistance;
     vol = audio.volume;
     if (player.currentWeapon == 0)
         aim = false;
         
     if (standAnims.length!=0) SetupAnimation(standAnims, "stand", 2, standAnimsSpeed);
     if (standAimAnims.length!=0) SetupAnimation(standAimAnims, "standAim", 2, standAnimsSpeed);
     if (standShootAnims.length!=0) SetupAnimation(standShootAnims, "standShoot", 4, standAnimsSpeed);
     if (walkAnims.length!=0) SetupAnimation(walkAnims, "walk", 2, walkAnimsSpeed);
     if (walkAimAnims.length!=0) SetupAnimation(walkAimAnims, "walkAim", 2, walkAnimsSpeed);
     if (walkShootAnims.length!=0) SetupAnimation(walkShootAnims, "walkShoot", 4, walkAnimsSpeed);
     if (runAnims.length!=0) SetupAnimation(runAnims, "run", 2, runAnimsSpeed);
     if (runAimAnims.length!=0) SetupAnimation(runAimAnims, "runAim", 2, runAnimsSpeed);
     if (runShootAnims.length!=0) SetupAnimation(runShootAnims, "runShoot", 4, runAnimsSpeed);
     if (reloadAnims.length!=0) SetupAnimation(reloadAnims, "reload", 4, 1.0);
     
     if (changeWeaponAnim!=null) {
         animatedMesh[changeWeaponAnim.name].wrapMode = WrapMode.Loop;
         animatedMesh[changeWeaponAnim.name].layer = 4;
     }
     // Only use jumping if the jumping animation has been set
     if (jumpingAnimation!=null) {
         animatedMesh[jumpingAnimation.name].wrapMode = WrapMode.ClampForever;
         animatedMesh[jumpingAnimation.name].layer = 3;
         doJumping = true;
         grounded = false;
     }
     // Only use idle animation if it has been set
     if (idleAnimations.length!=0) {
         for (var idleAnimation : AnimationClip in idleAnimations) {
             animatedMesh[idleAnimation.name].wrapMode = WrapMode.Loop;
             animatedMesh[idleAnimation.name].layer = 2;
         }
         doWaiting = true;
     }
     animatedMesh.playAutomatically = false;
 }
 
 function SetupAnimation (animationClip : AnimationClip[], newName : String, animLayer : int, speed : float) {
     for (var animI=0; animI<animationClip.Length; animI++) {
         if (animationClip[animI]!=null) {
             animatedMesh.AddClip(animationClip[animI], newName+animI);
             animatedMesh[newName+animI].wrapMode = WrapMode.Loop;
             animatedMesh[newName+animI].layer = animLayer;
             animatedMesh[newName+animI].speed = speed;
         }
     }
 }
 
 function Update () {
     armIK = GetComponent("ArmIK");
     
     if (cam.downSight || (Input.GetKey("left shift") || Input.GetKey("right shift")) != defaultIsWalk) {
         c.groundSpeed = (crouch || cam.downSight) ? curGroundSpeed * crouchMultiplier * walkMultiplier : curGroundSpeed * walkMultiplier;
         run = false;
     } else if (!cam.downSight) {
         c.groundSpeed = (crouch) ? curGroundSpeed * crouchMultiplier : curGroundSpeed;
         run = true;
     }
     
     cam.headBobDistance = (crouch || cam.downSight) ? curHeadBobDist * crouchMultiplier : curHeadBobDist;
     
     // CrossFade quick to jumping animation while not grounded
     if (doJumping) {
         // If the jump button has been pressed
         if (c.jumping) {
             grounded = false;
             jump = true;
             if (c.superJump)
                 superJump = true;
             // Fade to jumping animation quickly
             animatedMesh.CrossFade(jumpingAnimation.name, 0.1);
             animatedMesh[jumpingAnimation.name].time = 0;
             animatedMesh[jumpingAnimation.name].wrapMode = WrapMode.ClampForever;
         }
         // If the character has walked over a ledge and is now in air
         else if (grounded && !c.grounded) {
             grounded = false;
         }
         // If the character has landed on the ground again
         else if (!grounded && c.grounded && (!jump || (jump && fallingTimer>fallTimeThreshold))) {
             if (jumpSound) {
                 if (jumpingSound!=null)
                     audio.PlayOneShot(jumpingSound, vol);
                 jumpSound = false;
             }
             if (injured) {
                 BroadcastMessage("ApplyDamage", 0.5 * player.maximumHitPoints);
                 injured = false;
             }
             if (dead) {
                 BroadcastMessage("ApplyDamage", 2.0 * player.maximumHitPoints);
                 dead = false;
             }
             // Fade to locomotion motion group quickly
             animatedMesh.Stop(jumpingAnimation.name);
             fallingTimer = 0;
             jump = false;
             superJump = false;
             grounded = true;
         }
         // If the character is jumping or falling
         else if (!grounded && fallingTimer<fallTimeThreshold) {
             fallingTimer += Time.deltaTime;
             if (fallingTimer>=fallTimeThreshold && !jump) {
                 // Fade to jumping motion group slowly
                 animatedMesh.CrossFade(jumpingAnimation.name, 0.2);
                 animatedMesh[jumpingAnimation.name].time = 0;
                 animatedMesh[jumpingAnimation.name].wrapMode = WrapMode.ClampForever;
             }
         }
         else if (!grounded && fallingTimer>fallTimeThreshold) {
             fallingTimer += Time.deltaTime;
             if (fallingTimer>0.5)
                 jumpSound = true;
             if (fallingTimer>injuredTimeThreshold && !superJump && fallingDamage)
                 injured = true;
             if (fallingTimer>deadTimeThreshold && !superJump && fallingDamage)
                 dead = true;
         }
     }
     
     // CrossFade to waiting animation when inactive for a little while
     if (doWaiting) {
         if (rb.velocity.magnitude<0.3 && !aim && !busy && !crouch) {
             idleTimer += Time.deltaTime;
             if (idleTimer>3 && rb.velocity.magnitude<0.3 && !aim && !busy && !crouch) {
                 var randomNumber : int = Random.Range(0, idleAnimations.length);
                 var waitingAnimation : String;
                 waitingAnimation = idleAnimations[randomNumber].name;
                 if (idleSounds.length!=0)
                     audio.clip = idleSounds[randomNumber];
                 // if the idle animation is not in the middle of playing
                 if (
                     animatedMesh[waitingAnimation].time==0
                     || animatedMesh[waitingAnimation].time>=animatedMesh[waitingAnimation].length
                 ) {
                     // Then rewind and play it
                     animatedMesh[waitingAnimation].time = 0;
                     animatedMesh.CrossFade(waitingAnimation, 0.3);
                     animatedMesh[waitingAnimation].wrapMode = WrapMode.Loop;
                     
                     if (idleSounds.length!=0) {
 //                        audio.loop = true;
                         audio.volume = vol;
                         audio.Play();
                     }
                     waiting = true;
                 }
                 // Don't play again for a little random while
                 idleTimer = -(2+4*Random.value);
             }
         }
         // If we have started to move again
         else if ((rb.velocity.magnitude>=0.3 || aim || busy || crouch || !grounded) && waiting) {
             // Crossfade to locomotion
             animatedMesh.Stop(waitingAnimation);
             idleTimer = 0;
             waiting = false;
         }
     }
 
     // Play the aiming animation
     if (Screen.lockCursor && Input.GetButtonDown ("DownSight") && !aim) {
         lastFireTime = Time.time;
         aim = true;
     } else if (Screen.lockCursor && Input.GetButtonDown ("DownSight") && aim) {
         aim = false;
     }
     
     // Play the shoot animation
     if (Screen.lockCursor && Input.GetButtonDown ("Fire1") && aim && !busy) {
         shoot = true;
     } else if (Screen.lockCursor && Input.GetButtonDown ("Fire1") && !aim) {
         lastFireTime = Time.time;
         shoot = false;
         aim = true;
     }
     
     // Fire the gun
     if (Screen.lockCursor && Input.GetButton ("Fire1") && aim && shoot) {
         BroadcastMessage("Fire", SendMessageOptions.DontRequireReceiver);
         lastFireTime = Time.time;
     }
     
     // Stop the shoot animation
     if (Input.GetButtonUp ("Fire1") && shoot) {
         shoot = false;
     }
     
     if (shoot) {
         if (rb.velocity.magnitude>0.6 && !run && walkShootAnims[player.currentWeapon]!=null) {
             if (animatedMesh["walkShoot"+player.currentWeapon].length == animatedMesh["walkAim"+player.currentWeapon].length)
                 animatedMesh["walkShoot"+player.currentWeapon].time = animatedMesh["walkAim"+player.currentWeapon].time;
             if (player.currentWeapon == 0)
                 animatedMesh.CrossFade("walkShoot"+player.currentWeapon, 0.2);
             else
                 animatedMesh.CrossFade("walkShoot"+player.currentWeapon, 0.0);
         } else if (rb.velocity.magnitude>0.6 && run && runShootAnims[player.currentWeapon]!=null) {
             if (animatedMesh["runShoot"+player.currentWeapon].length == animatedMesh["runAim"+player.currentWeapon].length)
                 animatedMesh["runShoot"+player.currentWeapon].time = animatedMesh["runAim"+player.currentWeapon].time;
             if (player.currentWeapon == 0)
                 animatedMesh.CrossFade("runShoot"+player.currentWeapon, 0.2);
             else
                 animatedMesh.CrossFade("runShoot"+player.currentWeapon, 0.0);
         } else if (standShootAnims[player.currentWeapon]!=null) {
             if (animatedMesh["standShoot"+player.currentWeapon].length == animatedMesh["standAim"+player.currentWeapon].length)
                 animatedMesh["standShoot"+player.currentWeapon].time = animatedMesh["standAim"+player.currentWeapon].time;
             if (player.currentWeapon == 0)
                 animatedMesh.CrossFade("standShoot"+player.currentWeapon, 0.2);
             else
                 animatedMesh.CrossFade("standShoot"+player.currentWeapon, 0.0);
         }
     } else {
         if (walkShootAnims[player.currentWeapon]!=null && animatedMesh.IsPlaying("walkShoot"+player.currentWeapon))
             animatedMesh.Stop("walkShoot"+player.currentWeapon);
         else if (runShootAnims[player.currentWeapon]!=null && animatedMesh.IsPlaying("runShoot"+player.currentWeapon))
             animatedMesh.Stop("runShoot"+player.currentWeapon);
         else if (standShootAnims[player.currentWeapon]!=null && animatedMesh.IsPlaying("standShoot"+player.currentWeapon))
             animatedMesh.Stop("standShoot"+player.currentWeapon);
     }
     
     if (rb.velocity.magnitude>0.6 && !run) {
         if (!aim && walkAnims[player.currentWeapon]!=null)
             animatedMesh.CrossFade("walk"+player.currentWeapon, 0.2);
         else if (walkAimAnims[player.currentWeapon]!=null)
             animatedMesh.CrossFade("walkAim"+player.currentWeapon, 0.2);
         cam.headBobSpeed = walkAnimsSpeed * (2*Mathf.PI - Mathf.PI)/(0.5 * walkHeadBobMultiplier * animatedMesh["walkAim"+player.currentWeapon].length);
         if (doJumping && grounded && Time.time > footstepTimer) {
             if (leftFoot!=null && swapFoot) {
                 if (!c.ladderClimbing)
                     BroadcastMessage("FootPrint", leftFoot, SendMessageOptions.DontRequireReceiver);
                 swapFoot = !swapFoot;
             } else if (rightFoot!=null) {
                 if (!c.ladderClimbing)
                     BroadcastMessage("FootPrint", rightFoot, SendMessageOptions.DontRequireReceiver);
                 swapFoot = !swapFoot;
             }
             BroadcastMessage("OnFootStrike", SendMessageOptions.DontRequireReceiver);
             footstepTimer = Time.time + 0.5 * walkHeadBobMultiplier * animatedMesh["walkAim"+player.currentWeapon].length/walkAnimsSpeed;
         }
     } else if (rb.velocity.magnitude>0.6 && run) {
         if (!aim && runAnims[player.currentWeapon]!=null)
             animatedMesh.CrossFade("run"+player.currentWeapon, 0.2);
         else if (runAimAnims[player.currentWeapon]!=null)
             animatedMesh.CrossFade("runAim"+player.currentWeapon, 0.2);
         cam.headBobSpeed = runAnimsSpeed * (2*Mathf.PI - Mathf.PI)/(0.5 * runHeadBobMultiplier * animatedMesh["runAim"+player.currentWeapon].length);
         if (doJumping && grounded && Time.time > footstepTimer) {
             if (leftFoot!=null && swapFoot) {
                 if (!c.ladderClimbing)
                     BroadcastMessage("FootPrint", leftFoot, SendMessageOptions.DontRequireReceiver);
                 swapFoot = !swapFoot;
             } else if (rightFoot!=null) {
                 if (!c.ladderClimbing)
                     BroadcastMessage("FootPrint", rightFoot, SendMessageOptions.DontRequireReceiver);
                 swapFoot = !swapFoot;
             }
             BroadcastMessage("OnFootStrike", SendMessageOptions.DontRequireReceiver);
             footstepTimer = Time.time + 0.5 * runHeadBobMultiplier * animatedMesh["runAim"+player.currentWeapon].length/runAnimsSpeed;
         }
     } else if (!waiting) {
         if (!aim && standAnims[player.currentWeapon]!=null)
             animatedMesh.CrossFade("stand"+player.currentWeapon, 0.2);
         else if (standAimAnims[player.currentWeapon]!=null)
             animatedMesh.CrossFade("standAim"+player.currentWeapon, 0.2);
     }
     
     if (armIK!=null && player.currentWeapon != 0 && player.weapon[player.currentWeapon].leftArmPos!=null && alwaysSnapHandToWeapon
     && !aim && !busy && ((grounded  && !waiting) || (includingJump  && !grounded) || (includingIdle && waiting))) {
         armIK.aimWeapon = player.weapon[player.currentWeapon].leftArmPos;
         armIK.adjustment = 1;
     } else if (armIK!=null && alwaysSnapHandToWeapon && (!aim || busy)) {
         armIK.adjustment = 0;
     }
     
     if (aim && !busy) {
         if (player.currentWeapon != 0) {
             if (armIK!=null && player.weapon[player.currentWeapon].leftArmPos!=null) {
                 armIK.aimWeapon = player.weapon[player.currentWeapon].leftArmPos;
                 armIK.adjustment = 1;
             }
             if (!CameraAimTargets.aimed) {
                 crosshair.Fade(false);
                 cam.downSight = false;
             } else if (!cam.downSight)
                 crosshair.Fade(true);
             for (var aimWeapon : AimWeapons in aimWeapons)
                 aimWeapon.on = true;
         }
     } else {
         if (armIK!=null && !alwaysSnapHandToWeapon)
             armIK.adjustment = 0;
         crosshair.Fade(false);
         for (var aimWeapon : AimWeapons in aimWeapons)
             aimWeapon.on = false;
     }
     
     if (cam.downSight) {
         aim = true;
         crosshair.Fade(false);
         lastFireTime = Time.time;
     }
     
     if (aim && aimTime > 0 && Time.time - lastFireTime > aimTime && rb.velocity.magnitude > 0.6) {
         aim = false;
     }
     
     if (player.currentWeapon == 0)
         aim = false;
         
     // Play the sit animation
     var newPos = Mathf.SmoothDamp(playerObject.localPosition.y, playerObjectPos, playerObjectVelocity, 0.2);
     playerObject.localPosition.y = newPos;
     if (Input.GetButtonDown ("Crouch")) {
         Crouch ();
     }
 }
 
 function Crouch () {
     if (!crouch) {
         collider.height = crouchedColliderHeight;
         collider.center.y = crouchedColliderCenterY;
         playerObjectPos = crouchedPlayerObjectY;
         crouch = true;
     } else {
         collider.height = currColliderHeight;
         collider.center.y = currColliderCenterY;
         playerObjectPos = currPlayerObjectY;
         crouch = false;
     }
 }
 
 function Reloading (reloadTime : float) {
     busy = true;
     shoot = false;
     if (reloadAnims[player.currentWeapon]!=null)
         animatedMesh.CrossFade("reload"+player.currentWeapon, 0.2);
     yield WaitForSeconds(reloadTime);
     if (reloadAnims[player.currentWeapon]!=null && animatedMesh.IsPlaying("reload"+player.currentWeapon))
         animatedMesh.Stop("reload"+player.currentWeapon);
     gunIsEmpty = false;
     busy = false;
 }
 
 function WeaponChanged () {
     busy = true;
     shoot = false;
     if (animatedMesh == null || !animatedMesh.gameObject.active)
         animatedMesh = gameObject.GetComponentInChildren(Animation);
     if (changeWeaponAnim!=null)
         animatedMesh.CrossFade(changeWeaponAnim.name, 0.2);
     if (setTimeForChange)
         yield WaitForSeconds(timeForChangeWeapon);
     else
         yield WaitForSeconds(animatedMesh[changeWeaponAnim.name].length);
     if (changeWeaponAnim!=null && animatedMesh.IsPlaying(changeWeaponAnim.name))
         animatedMesh.Stop(changeWeaponAnim.name);
     if (player.currentWeapon == 0)
         aim = false;
     gunIsEmpty = false;
     busy = false;
 }
 
 function DeactivateBomb (deactivateTime : float) {
     busy = true;
     shoot = false;
     var wasCrouch : boolean = false;
     if (!crouch)
         Crouch ();
     else
         wasCrouch = true;
     yield WaitForSeconds(deactivateTime);
     if (!wasCrouch)
         Crouch ();
     busy = false;
 }
 
 function GunIsEmpty () {
     gunIsEmpty = true;
     shoot = false;
 }
 
 function IsDead () {
     if (doJumping) {
         grounded = false;
         jumpSound = false;
         injured = false;
         dead = false;
     }
     aim = false;
     shoot = false;
     if (crouch)
         Crouch ();
     if (Camera.main.gameObject.GetComponent(pauseFilterEffect) != null)
         Camera.main.gameObject.GetComponent(pauseFilterEffect).enabled = false;
 }

Two errors: 1.NullReferenceException: Object reference not set to an instance of an object FPSPlayer.Start () (at Assets/Scripts/Player/FPSPlayer.js:67)

2.NullReferenceException: Object reference not set to an instance of an object FPSPlayer.UpdateGUI () (at Assets/Scripts/Player/FPSPlayer.js:269) FPSPlayer.LateUpdate () (at Assets/Scripts/Player/FPSPlayer.js:84)

 @script AddComponentMenu("Shooter Engine/Player/FPS Player")
 
 var maximumHitPoints : float = 100.0;
 var hitPoints : float = 100.0;
 var lives : int = 5;
 var deadReplacement : Transform;
 var deadOffsetY : float = 0.0;
 var deadTime : float = 3.0;
 var deathSlowsTime : boolean = true;
 
 var painLittle : AudioClip;
 var painBig : AudioClip;
 var die : AudioClip[];
 var weaponChangeSound : AudioClip;
 
 var enemiesGUI : GUIText;
 var bossesGUI : GUIText;
 var healthGUI : GUITexture;
 var livesGUI : GUIText;
 var itemsGUI : GUIText;
 var burstModeGUI : GUIText;
 var bulletsLeftGUI : GUIText;
 var clipsGUI : GUIText;
 var infoTextGUI : GUIText;
 var weaponGUI : GUITexture;
 var crosshairGUI : GUITexture;
 var scopeGUI : GUITexture;
 
 var weapon : UniversalGun[] = new UniversalGun[1];
 var hasWeapon : boolean[] = new boolean[1];
 var weaponMaxClips : int[] = new int[1];
 var weaponTextures : Texture[] = new Texture[1];
 var crosshairTextures : Texture[] = new Texture[1];
 var currentWeapon : int = 1;
 
 var hasFirstKey : boolean = false;
 var hasSecondKey : boolean = false;
 var hasThirdKey : boolean = false;
 
 @HideInInspector var firstKeyUsed : boolean = false;
 @HideInInspector var secondKeyUsed : boolean = false;
 @HideInInspector var thirdKeyUsed : boolean = false;
 @HideInInspector var isDead : boolean = false;
 @HideInInspector var levelStateMachine : LevelStatus;        // link to script that handles the level-complete sequence.
 @HideInInspector var remainingItems : int;    // total number to pick up on this level. Grabbed from LevelStatus.
 
 private var healthGUIWidth : float = 0.0;
 private var gotHitTimer : float = -1.0;
 private var vol : float;
 private var gameStatus : GameStatus;
 private var gameOverLevel : String;
 private var fpsAnim : FPSAnimation;
 
 function Start () {
     fpsAnim = GetComponent(FPSAnimation);
     gameStatus = FindObjectOfType(GameStatus);
     levelStateMachine = FindObjectOfType(LevelStatus);
     if (!gameStatus)
         Debug.Log("GameStatus script not found!");
     if (!levelStateMachine)
         Debug.Log("LevelStatus script not found!");
     if (deadReplacement != null && deadReplacement.GetComponent(TimedObjectDestructor) != null)
         deadReplacement.GetComponent(TimedObjectDestructor).timeOut = deadTime;
     if (healthGUI != null)
         healthGUIWidth = healthGUI.pixelInset.width;
         
     gameOverLevel = gameStatus.gameOverLevel;
     remainingItems = levelStateMachine.itemsNeeded;
     vol = audio.volume;
     
 //    /*
     var coms = gameObject.GetComponentsInChildren(Behaviour);
     for (var com : Behaviour in coms)
         com.enabled = false;
     GetComponent(FPSPlayer).enabled = true;
     for (var com : Behaviour in coms)
         com.enabled = true;
 //    */
 }
 
 function LateUpdate () {
     // Update gui every frame
     // We do this in late update to make sure machine guns etc. were already executed
     UpdateGUI();
 }
 
 function FoundItem (numFound: int) {
     gameStatus.itemsFound += numFound;
     remainingItems -= numFound;
     
     // NOTE: We are deliberately not clamping this value to zero. 
     // This allows for levels where the number of pickups is greater than the target number needed. 
     // This also lets us speed up the testing process by temporarily reducing the collecatbles needed. 
     // Our HUD will clamp to zero for us.
     
     if (remainingItems == 0)
         levelStateMachine.UnlockLevelExit(); // ...and let our player out of the level.
 }
 
 // Utility function used by HUD script:
 function GetRemainingItems () : int {
     return remainingItems;
 }
 
 function LevelCompleted () {
     levelStateMachine.LevelCompleted();
 }
 
 function WeaponChanged () {
     if (weaponChangeSound != null)
         audio.PlayOneShot(weaponChangeSound, vol);
 }
 
 function ApplyDamage (damage : float) {
     if (hitPoints < 0.0 || isDead)
         return;
         
     // Apply damage
     hitPoints -= damage;
     
     // Play pain sound when getting hit - but don't play so often
     if (painBig != null && painLittle != null && Time.time > gotHitTimer) {
         // Play a big pain sound
         if (hitPoints < maximumHitPoints * 0.2 || damage > 20) {
             audio.PlayOneShot(painBig, 1.0 / vol);
             gotHitTimer = Time.time + Random.Range(painBig.length * 2, painBig.length * 3);
         } else {
             // Play a small pain sound
             audio.PlayOneShot(painLittle, 1.0 / vol);
             gotHitTimer = Time.time + Random.Range(painLittle.length * 2, painLittle.length * 3);
         }
     }
     
     // Are we dead?
     if (hitPoints < 0.0)
         Die();
 }
 
 function Die () {
     if (isDead)
         return;
         
     isDead = true;
     
     lives--;
     GameStatus.playerDeaths ++;
     
     if (die.length != 0)
         AudioSource.PlayClipAtPoint(die[Random.Range(0, die.length)], transform.position, vol);
         
     // Disable all script behaviours (Essentially deactivating player control)
     var coms = gameObject.GetComponentsInChildren(Behaviour);
     for (var com : Behaviour in coms) {
         com.enabled = false;
     }
     GetComponent(FPSPlayer).enabled = true;
     // Deactivate all gameobjects
     for (var i=0;i<transform.childCount;i++) {
         transform.GetChild(i).gameObject.SetActiveRecursively(false);
     }
     
     // Replace ourselves with the dead body
     if (deadReplacement) {
         if (fpsAnim != null) {
             var dead : Transform = Instantiate(deadReplacement, transform.position + Vector3.up * deadOffsetY, transform.rotation);
             dead.BroadcastMessage("SelectWeapon", currentWeapon, SendMessageOptions.DontRequireReceiver);
         } else {
             var deadR : Transform = Instantiate(deadReplacement, transform.position, transform.rotation);
             // Copy position & rotation from the old hierarchy into the dead replacement
             CopyTransformsRecurse(transform, deadR);
             deadR.BroadcastMessage("SelectWeapon", currentWeapon, SendMessageOptions.DontRequireReceiver);
         }
     }
     
     if (deathSlowsTime) {
         var timeScaler : SlowMo = FindObjectOfType(SlowMo);
         timeScaler.timeMultiplier = 0.25;
     }
     
     if (lives < 0) {
         timeScaler.timeMultiplier = 1.0;
         Time.timeScale = 1.0;
 //        LevelLoadFade.FadeAndLoadLevel(Application.loadedLevel, Color.black, 2.0);
         LevelLoadFade.FadeAndLoadLevel(gameOverLevel, Color.black, 2.0);
     }
     
     // If we've reached here, the player still has lives remaining, so respawn.
     // Relocate the player. We need to do this or the camera will keep trying to focus on the (invisible) player where he's standing on top of the FalloutDeath box collider.
     transform.position = Respawn.currentRespawn.transform.position;
     transform.rotation.eulerAngles.y = Respawn.currentRespawn.transform.rotation.eulerAngles.y;
     if (fpsAnim != null)
         rigidbody.isKinematic = true;
         
     yield WaitForSeconds(deadTime);    // give the sound time to complete. 
     
     // Show the player again, ready for...
     for (var j=0;j<transform.childCount;j++) {
         transform.GetChild(j).gameObject.SetActiveRecursively(true);
     }
     // Enable all script behaviours (And activating player control)
     for (var com : Behaviour in coms) {
         com.enabled = true;
     }
     
     var aus = gameObject.GetComponentsInChildren(AudioSource, true);
     for (var au : AudioSource in aus) {
         au.pitch = 1.0;
     }
     
     hitPoints = maximumHitPoints;
     BroadcastMessage("IsDead");
     BroadcastMessage("SelectCurrentWeapon", currentWeapon);
     if (fpsAnim != null)
         rigidbody.isKinematic = false;
     if (deathSlowsTime)
         timeScaler.timeMultiplier = 1.0;
         
     // ... the respawn point to play it's particle effect
     Respawn.currentRespawn.FireEffect();
     
     isDead = false;
 }
 
 function UpdateGUI () {
     // Update health gui
     // The health gui is rendered using a overlay texture which is scaled down based on health
     // - Calculate fraction of how much health we have left (0...1)
     var healthFraction : float = Mathf.Clamp01(hitPoints / maximumHitPoints);
     
     // - Adjust maximum pixel inset based on it
     if (healthGUI != null)
         healthGUI.pixelInset.xMax = healthGUI.pixelInset.xMin + healthGUIWidth * healthFraction;
         
     // Update lives gui
     if (livesGUI != null) {
         if (lives > 0)
             livesGUI.text = lives.ToString();
         else
             livesGUI.text = "";
     }
     
     if (crosshairGUI != null && crosshairTextures[currentWeapon] != null && !isDead) {
         crosshairGUI.enabled = true;
         crosshairGUI.texture = crosshairTextures[currentWeapon];
     } else if (crosshairGUI != null) {
         crosshairGUI.enabled = false;
     }
     
     if (weaponGUI != null && weaponTextures[currentWeapon] != null) {
         weaponGUI.enabled = true;
         weaponGUI.texture = weaponTextures[currentWeapon];
     } else if (weaponGUI != null) {
         weaponGUI.enabled = false;
     }
     
     // Update machine gun gui
     // Machine gun gui is simply drawn with a bullet counter text
     if (weapon[currentWeapon] != null && currentWeapon != 0) {
         if (burstModeGUI != null) burstModeGUI.text = weapon[currentWeapon].burstMode.ToString();
         if (bulletsLeftGUI != null) bulletsLeftGUI.text = weapon[currentWeapon].GetBulletsLeft().ToString();
         if (clipsGUI != null) clipsGUI.text = weapon[currentWeapon].GetClips().ToString();
     } else {
         if (burstModeGUI != null) burstModeGUI.text = "";
         if (bulletsLeftGUI != null) bulletsLeftGUI.text = "";
         if (clipsGUI != null) clipsGUI.text = "";
     }
     
     if (itemsGUI != null) {
         if (levelStateMachine.itemsNeeded > 0)
             itemsGUI.text = levelStateMachine.itemsNeeded - remainingItems+"*"+levelStateMachine.itemsNeeded;
         else
             itemsGUI.text = "";
     }
     
     if (enemiesGUI != null) {
         if (GameStatus.enemiesOnLevel > 0)
             enemiesGUI.text = "Enemies: "+GameStatus.enemiesKilled+"*"+GameStatus.enemiesOnLevel;
         else
             enemiesGUI.text = "";
     }
     
     if (bossesGUI != null) {
         if (GameStatus.bossesOnLevel > 0)
             bossesGUI.text = "Bosses: "+GameStatus.bossesKilled+"*"+GameStatus.bossesOnLevel;
         else
             bossesGUI.text = "";
     }
     
     if (scopeGUI != null && weapon[currentWeapon] != null && currentWeapon != 0 && weapon[currentWeapon].scopeTexture != null && weapon[currentWeapon].inScope && !isDead) {
         scopeGUI.enabled = true;
         scopeGUI.texture = weapon[currentWeapon].scopeTexture;
         var k : float = scopeGUI.pixelInset.width/scopeGUI.pixelInset.height;
         scopeGUI.pixelInset.width = Screen.height * k;
         scopeGUI.pixelInset.height = Screen.height;
         scopeGUI.pixelInset.x = -(scopeGUI.pixelInset.width * 0.5);
         scopeGUI.pixelInset.y = -(scopeGUI.pixelInset.height * 0.5);
 //        var scopeTarget : Transform = weapon[currentWeapon].sightTarget;
 //        var scopeDirection : Vector3 = scopeTarget.TransformDirection(Vector3.forward);
 //        scopeGUI.transform.position = camera.main.WorldToViewportPoint(scopeTarget.position + scopeDirection * 0.1);
 //        scopeGUI.transform.position.z = 0.0;
     } else if (scopeGUI != null) {
         scopeGUI.enabled = false;
     }
 }
 
 function InfoText (text : String) {
     if (infoTextGUI != null)
         infoTextGUI.gameObject.GetComponent(TimedFadeText).Fade(text);
 }
 
 function CopyTransformsRecurse (src : Transform,  dst : Transform) {
     if (dst.collider!=null)
         Physics.IgnoreCollision (dst.collider, collider);
     dst.position = src.position;
     dst.rotation = src.rotation;
     
     for (var child : Transform in dst) {
         // Match the transform with the same name
         var curSrc = src.Find(child.name);
         if (curSrc)
             CopyTransformsRecurse(curSrc, child);
     }
 }


 
Comment
Add comment · Show 5
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Loius · Jan 19, 2013 at 06:20 PM 1
Share

Null references means you're trying to use the . operator on something that hasn't been initialized. The errors tell you exactly which lines are causing the problem; I can't speak for anyone else but I don't feel like hunting through four pages of code.

avatar image iwaldrop · Jan 19, 2013 at 06:53 PM 0
Share

I feel the same as Louis...that's just way too much code to hunt through. Just look at the line number that your console tells you, see which variable it's talking about, and make sure you initialize it before you try and use it. OR, you can do something like:

 if (SwitchWeapons != null)
 {
     // do something with SwitchWeapons
 }
avatar image FL · Jan 20, 2013 at 12:04 AM 0
Share

You probably needs to sets some objects by the inspector.

avatar image sdgd · Jan 20, 2013 at 02:39 AM 0
Share

yeah well reading whole code would take at least 1 hour

I usually post the problem of code what I want to achieve in maybe 3-5 lines

after that I place full code where I want to implant that code

I'm sorry I can't help you much

avatar image sdgd · Jan 20, 2013 at 02:44 AM 0
Share

and I strongly recommend to start making your own games on your own

people do errors and fixing other errors is just time wasting

I think but aint sure but that you'll create your own code faster than repair all that problems especially if you don't have experience

I get some problems and I know the problems as I've pinpointed them in 3 - 5 lines and start searching wiki and A/Q

after few hours of trying usually I succeed but IF I don't I ask Question here

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

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

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

12 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

NullReferenceException? 2 Answers

Null Reference Expantion 1 Answer

Null Reference Exception For Blocks C# 1 Answer

No idea what happend to unity (See pictures) 0 Answers

Physics2D.Linecast and Physics2D.Raycast don't seem to return null 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges