Search Unity

Problem with pickup clips and ammo!!!!!!!!

Discussion in 'Scripting' started by Kryber, Apr 16, 2013.

  1. Kryber

    Kryber

    Joined:
    Apr 14, 2013
    Posts:
    92
    Hello guys, I have a problem with my script about pickup clips (and bullets) and it gives me the following error: NullReferenceException: Object reference not set to an instance of an object
    TakeAmmo.Update () (at Assets / ScriptsDB / AIScripts / TakeAmmo.js: 57)
    Help me, please

    Code (csharp):
    1. var obj1 : Transform; //the gameobject (Clip)
    2.  
    3.  
    4.  
    5. var obj2 : Transform; //my Player
    6.  
    7.  
    8.  
    9. var Bar : float;
    10.  
    11.  
    12.  
    13.  
    14.  
    15.  
    16.  
    17.  
    18.  
    19. function Start ()
    20.  
    21. {
    22.  
    23.     var Bar = (Screen.width / 1);
    24.  
    25. }
    26.  
    27.  
    28.  
    29. function Update ()
    30.  
    31. {
    32.  
    33.     var dist = Vector3.Distance( obj1.position,obj2.position );
    34.  
    35.        
    36.  
    37.     if(dist < 4)
    38.  
    39.     {
    40.  
    41.    
    42.  
    43.    
    44.  
    45.         if(Input.GetKeyDown ("f")) //if i press f
    46.  
    47.         {
    48.  
    49.            
    50.  
    51.            
    52.  
    53.             var script : gunscript = GetComponent(gunscript); //change the variable ammo in clips += 60
    54.  
    55.            
    56.  
    57.             script.clips += 60;
    58.  
    59.            
    60.  
    61.             Destroy(obj1); // and destroy the gameobject (Clip)
    62.  
    63.         }
    64.  
    65.  
    66.  
    67.     }
    68.  
    69. }
    70.  
    71.  
    72.  
    73.  
    74.  
    75.  
    76.  
    77. function OnGUI()
    78.  
    79. {  
    80.  
    81.     var dist = Vector3.Distance( obj1.position,obj2.position );
    82.  
    83.        
    84.  
    85.     if(dist < 4)
    86.  
    87.     {
    88.  
    89.        
    90.  
    91.         GUI.Box (new Rect(10, 740, Bar, 40), "Ammo for M4A1, F to pickup");
    92.  
    93.        
    94.  
    95.        
    96.  
    97.            
    98.  
    99.     }      
    100.  
    101.    
    102.  
    103.    
    104.  
    105. }
    it is the line of script for change umber of clips

    [/CODE]
    var clips : int = 20;[/CODE]

    I think the problem is ": int".

    HELP!
     
    Last edited: Apr 16, 2013
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    Have you put something in obj1 in the inspector?

    edit: and for that matter, you're destroying obj1 when you press f, so any subsequent presses of f will error since obj1 doesn't exist any more...
     
  3. Kryber

    Kryber

    Joined:
    Apr 14, 2013
    Posts:
    92
    Yes i have put the gameobject clip in the ispector and I modified the script in this but I got a different error, namely Assets/ScriptsDB/AIScripts/TakeAmmo.js(39,13): BCE0034: Expressions in statements must only be executed for their side-effects.


    var obj1 : Transform; //the gameobject (Clip)

    var obj2 : Transform; //my Player

    var Bar : float;


    function Start ()

    {

    var Bar = (Screen.width / 1);

    }


    function Update ()

    {

    var dist = Vector3.Distance( obj1.position,obj2.position );


    if(dist < 4)

    {

    if(Input.GetKeyDown ("f")) //if i press f

    {

    var script : gunscript = GetComponent(gunscript); //change the variable ammo in clips += 60

    script.clips += 60;



    DestroyClip; //39

    }



    }

    }


    function OnGUI()

    {

    var dist = Vector3.Distance( obj1.position,obj2.position );

    if(dist < 4)

    {
    GUI.Box (new Rect(10, 740, Bar, 40), "Ammo for M4A1, F to pickup");

    }


    }

    function DestroyClip ()
    {


    Destroy(obj1);

    }
     
  4. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    that error is complaining about you needing the () on the end of the call to DestroyClip...
     
  5. Kryber

    Kryber

    Joined:
    Apr 14, 2013
    Posts:
    92
    Mmmmm Yes, I solved that problem but it remains one of the NullReferenceExeption
    script.Clips + = 60
     
  6. Whatbadguy

    Whatbadguy

    Joined:
    Apr 10, 2011
    Posts:
    166
    Then either 'script' or the variable 'Clips' doesn't exist.
     
  7. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    what is gunscript attached to? is it attached to the same object as this script? if it's attached to a child object you're asking the wrong gameobject for the component.

    are you sure it's called gunscript and not GunScript or gunScript? does it have a variable called clips (and not clip)... that kind of thing.

    The null exception error is basically a "I can't find what you've told me is there" kind of error so it's time to check everything is capitalised correctly and is attached to the right objects etc.
     
  8. Kryber

    Kryber

    Joined:
    Apr 14, 2013
    Posts:
    92
    This is the biggest script (gunscript) This script it attached to weapon in the weapon camera in the first person controller.

    //Gun Types
    enum gunTypes {gun, launcher, sustained, melee}
    var gunType : gunTypes = gunTypes.gun;

    //Launcher-Specific Variables
    var projectile : Rigidbody;
    var initialSpeed = 20.0;
    var projectileCount : int = 1;
    var launchPosition : GameObject;

    //Gun-Specific Variables
    var range = 100.0;
    var force = 10.0;
    var damage = 5.0;
    var shotCount : int = 6;
    var burstFire : boolean = false;
    var burstCount : int = 1;
    var burstTime : float = .5;
    var penetrateVal : int = 1;
    //Sustained Fire (Laser) Specific Variables
    var damagePerSecond : float;
    var ammoPerSecond : float;
    var laserRange : float;
    var laserGFX : GameObject;
    static var takingOut : boolean = false;

    //Sustained Fire and Gun shared variables
    var kickbackZ : float = 0;
    private var startKickback : boolean = false;

    //General Variables
    private var hitParticles : ParticleEmitter;
    var ammoPerClip : int = 40;
    var clips : int = 20; <<<<<--------------------------------------------------------------------------HEREEEEEEEE
    var maxClips : int = 20;
    var reloadTime = 0.5;
    var reloadInTime = 0.5;
    var reloadOutTime = 0.5;
    var muzzleFlash : Renderer;
    var waitforReload = 0.00;
    var gunActive : boolean = false;
    var infiniteAmmo : boolean = false;
    var reloading : boolean = false;
    var ammoLeft : float = 0;
    var nextFireTime = 0.0;
    private var m_LastFrameShot = -1;
    private var muzzleFlashOn : boolean = false;
    private var mainCam : GameObject;
    private var weaponCam : GameObject;
    var kickbackAngle : float;
    var isPrimaryWeapon : boolean = true;
    private var primaryWeapon : gunscript;
    var secondaryWeapon : gunscript;
    var secondaryActive : boolean = false;
    var secondaryInterrupt : boolean = false;
    var secondaryFire : boolean = false;
    enum ammoTypes {byClip, byBullet}
    var ammoType : ammoTypes = ammoTypes.byClip;
    var shellEjection : boolean = false;
    var ejectorPosition : GameObject;
    var shell : GameObject;

    //Variables shared between launcher and Gun
    var fireRate = 0.05;
    static var crosshairSpread : float;
    private var shotSpread : float;
    private var actualSpread : float;
    var standardSpread = .1;
    private var spreadRate = .05;
    var maxSpread = .25;
    var crouchSpreadModifier = .7;
    var moveSpreadModifier = 1.5;
    var standardSpreadRate = .05;
    var aimSpreadRate = .01;
    var aimSpread = .01;
    var spDecRate = .05;
    var autoFire : boolean;
    var fireAnim : boolean = false;
    var progressiveReload : boolean = false;
    private var progressiveReloading : boolean = false;
    private var pReloadTime : float = 0;
    var delay : float = 0;
    private var inDelay : boolean = false;
    var hitBox : boolean = false;

    //Ammo Sharing
    var sharesAmmo : boolean = false;
    var shareLoadedAmmo : boolean = false;
    var ammoSetUsed : int = 0;
    var managerObject : GameObject;
    managerObject = GameObject.FindWithTag("Manager");


    //Sway
    var swayFactor : Vector3;
    private var walkSway1 : Vector3;
    private var walkSway2 : Vector3;
    private var swayTarget : int = 1;
    var swayRate : float = .5;
    private var player : GameObject;
    private var startPosition : Vector3;
    private var areSprinting : boolean = false;
    var aim : boolean = false;
    var aim1 : aimmode;

    function aiming () {
    shotSpread = aimSpread;
    spreadRate = aimSpreadRate;
    if(FPSWalkerDB.crouching)
    crouching();
    if(FPSWalkerDB.walking)
    walking();
    }

    function crouching () {
    shotSpread *= crouchSpreadModifier;
    spreadRate *= crouchSpreadModifier;
    }
    function walking () {
    shotSpread = Mathf.Max(standardSpread*moveSpreadModifier, shotSpread);
    spreadRate *= moveSpreadModifier;
    }
    function stopWalking () {
    spreadRate = standardSpreadRate;
    if(shotSpread < standardSpread)
    shotSpread = standardSpread;
    if(GetComponentInChildren(aimmode).aiming){
    spreadRate = aimSpreadRate;
    shotSpread = aimSpread;
    }
    if(shotSpread > maxSpread)
    shotSpread = maxSpread;

    }
    function stopAiming () {
    shotSpread = standardSpread;
    spreadRate = standardSpreadRate;
    if(FPSWalkerDB.crouching){
    crouching();
    }
    if(FPSWalkerDB.walking)
    walking();
    }
    function Cooldown () {
    if(FPSWalkerDB.crouching FPSWalkerDB.walking shotSpread > standardSpread*crouchSpreadModifier*moveSpreadModifier){
    shotSpread = Mathf.Max(standardSpread*crouchSpreadModifier*moveSpreadModifier, shotSpread - spDecRate);
    } else if(FPSWalkerDB.crouching shotSpread > standardSpread*crouchSpreadModifier){
    shotSpread = Mathf.Max(standardSpread*crouchSpreadModifier, shotSpread - spDecRate);
    } else if(FPSWalkerDB.walking shotSpread > standardSpread*moveSpreadModifier){
    shotSpread = Mathf.Max(standardSpread*moveSpreadModifier, shotSpread - spDecRate);
    } else if(shotSpread > standardSpread !FPSWalkerDB.walking !FPSWalkerDB.crouching){
    shotSpread = Mathf.Max(standardSpread, shotSpread - spDecRate);
    }
    if(laserGFX != null){
    laserGFX.active = false;
    if (audio) {
    audio.Stop();
    }
    }

    }

    function Start () {
    aim1 = GetComponentInChildren(aimmode);
    inDelay = false;
    hitBox = false;

    if(sharesAmmo){
    clips = managerObject.GetComponent(AmmoManager).clipsArray[ammoSetUsed];
    maxClips = managerObject.GetComponent(AmmoManager).maxClipsArray[ammoSetUsed];
    infiniteAmmo = managerObject.GetComponent(AmmoManager).infiniteArray[ammoSetUsed];

    }

    if(!isPrimaryWeapon){
    gunActive = false;
    var wpns = new Array();
    wpns = this.GetComponents(gunscript);
    for(var p : int = 0; p < wpns.length; p++){
    if(wpns[p].isPrimaryWeapon){
    primaryWeapon = wpns[p];
    }
    }
    }
    if(laserGFX != null)
    laserGFX.active = false;
    hitParticles = GetComponentInChildren(ParticleEmitter);
    shotSpread = standardSpread;
    spreadRate = standardSpreadRate;
    // We don't want to emit particles all the time, only when we hit something.
    if (hitParticles)
    hitParticles.emit = false;
    ammoLeft = ammoPerClip;
    SendMessage("updateAmmo", ammoLeft, SendMessageOptions.DontRequireReceiver);
    SendMessage("updateClips", clips, SendMessageOptions.DontRequireReceiver);
    player = GameObject.FindWithTag("Player");
    controller = player.GetComponent(Rigidbody);
    defineSwayPoints();
    startPosition = transform.localPosition;
    muzzleFlash.enabled = false;
    mainCam = GameObject.FindWithTag("MainCamera");
    weaponCam = GameObject.FindWithTag("WeaponCamera");
    }
    function Update () {
    if(progressiveReloading){
    if(ammoLeft < ammoPerClip){
    if(Time.time > pReloadTime){
    BroadcastMessage("ReloadAnim", reloadTime);
    pReloadTime = Time.time + reloadTime;
    ammoLeft++;
    clips--;
    SendMessage("updateAmmo", ammoLeft, SendMessageOptions.DontRequireReceiver);
    SendMessage("updateClips", clips, SendMessageOptions.DontRequireReceiver);
    }
    } else if(Time.time > pReloadTime) {
    progressiveReloading = false;
    BroadcastMessage("ReloadOut", reloadOutTime);
    reloading=false;
    if(aim)
    aim1.aim = true;
    aim1.canSwitchWeaponAim = true;
    ApplyToSharedAmmo();
    }
    }

    if(actualSpread != shotSpread){
    actualSpread += (shotSpread-actualSpread)*Time.deltaTime*16;
    }
    if(gunActive){
    if(!playerweapons.autoFire autoFire){
    SendMessageUpwards("FullAuto");
    }
    if(playerweapons.autoFire !autoFire){
    SendMessageUpwards("SemiAuto");
    }
    }
    }
    function LateUpdate() {
    if(shotSpread > maxSpread)
    shotSpread = maxSpread;

    if(gunActive)
    crosshairSpread = actualSpread*180/mainCam.camera.fieldOfView*Screen.height;

    if(!gunActive || reloading){
    if(laserGFX != null){
    laserGFX.active = false;
    if (audio) {
    audio.Stop();
    }
    }
    }

    if(Input.GetKeyDown("q") secondaryWeapon != null){
    if(!secondaryWeapon.gunActive){
    activateSecondary();
    } else if(secondaryWeapon.gunActive){
    activatePrimary();
    }
    }

    if(FPSWalkerDB.walking){
    walkSway();
    } else {
    resetPosition();
    }

    if (muzzleFlash muzzleFlashOn) {
    // We shot this frame, enable the muzzle flash
    var scoped : boolean = transform.Find("AimObject").GetComponent(aimmode).inScope;
    if (m_LastFrameShot == Time.frameCount) {
    if(!scoped)
    muzzleFlash.enabled = true;
    if (audio) {
    audio.Play();
    audio.loop = true;
    }
    } else {
    // We didn't, disable the muzzle flash
    muzzleFlash.enabled = false;
    muzzleFlashOn = false;

    // Play sound
    if (audio){
    audio.loop = false;
    }
    }
    }
    }
    function FireAlt () {
    if(!isPrimaryWeapon){
    AlignToSharedAmmo();
    gunActive = true;
    Fire();
    gunActive = false;
    }
    }
    function AlignToSharedAmmo () {
    if(sharesAmmo){
    clips = managerObject.GetComponent(AmmoManager).clipsArray[ammoSetUsed];
    maxClips = managerObject.GetComponent(AmmoManager).maxClipsArray[ammoSetUsed];
    infiniteAmmo = managerObject.GetComponent(AmmoManager).infiniteArray[ammoSetUsed];
    SendMessage("updateAmmo", ammoLeft, SendMessageOptions.DontRequireReceiver);
    SendMessage("updateClips", clips, SendMessageOptions.DontRequireReceiver);
    }

    }
    function ApplyToSharedAmmo () {
    if(sharesAmmo){
    managerObject.GetComponent(AmmoManager).clipsArray[ammoSetUsed] = clips;
    managerObject.GetComponent(AmmoManager).maxClipsArray[ammoSetUsed] = maxClips;
    managerObject.GetComponent(AmmoManager).infiniteArray[ammoSetUsed] = infiniteAmmo;
    }

    }
    function Fire2 () {
    if(isPrimaryWeapon secondaryWeapon != null gunActive secondaryWeapon.secondaryFire){
    ApplyToSharedAmmo();
    secondaryWeapon.FireAlt();

    }
    }
    function Fire () {
    if (!gunActive || areSprinting || inDelay)
    return;
    if(progressiveReloading){
    progressiveReloading = false;
    reloading = false;
    if(aim)
    aim1.aim = true;
    aim1.canSwitchWeaponAim = true;
    if(secondaryWeapon != null secondaryWeapon.secondaryFire !secondaryWeapon.secondaryInterrupt){
    secondaryWeapon.reloading = false;
    } else if(secondaryFire !secondaryInterrupt !isPrimaryWeapon){
    primaryWeapon.reloading = false;
    }

    }

    var b : int = 1; //variable to control burst fire

    if ((ammoLeft <= 0) || ( nextFireTime > Time.time ) || !gunActive || reloading){
    if(ammoLeft <=0){
    Reload();
    }
    return;
    }
    hitBox = true;

    if(gunType != gunTypes.sustained){
    if(burstFire){
    b = burstCount;
    } else {
    b = 1;
    }
    for(var i=0; i<b; i++){
    if(ammoLeft > 0){
    FireShot();
    ammoLeft--;
    if(fireRate<delay){
    nextFireTime = Time.time+delay;
    } else {
    nextFireTime = Time.time+fireRate;
    }
    if(secondaryWeapon != null secondaryWeapon.secondaryFire !secondaryWeapon.secondaryInterrupt){
    if(fireRate<delay){
    secondaryWeapon.nextFireTime = Time.time+delay;
    } else {
    secondaryWeapon.nextFireTime = Time.time+fireRate;
    }
    } else if(secondaryFire !secondaryInterrupt !isPrimaryWeapon){
    if(fireRate<delay){
    primaryWeapon.nextFireTime = Time.time+delay;
    } else {
    primaryWeapon.nextFireTime = Time.time+fireRate;
    }

    }
    if(burstFire i < (b-1)){
    if(burstTime/burstCount<delay){
    yield new WaitForSeconds(delay);
    } else {
    yield new WaitForSeconds(burstTime/burstCount);
    }
    }
    }
    }
    } else {
    FireLaser();
    var APS : float = ammoPerSecond*Time.deltaTime;
    ammoLeft -= APS;
    }
    ApplyToSharedAmmo();

    SendMessage("updateAmmo", ammoLeft, SendMessageOptions.DontRequireReceiver);
    SendMessage("updateClips", clips, SendMessageOptions.DontRequireReceiver);
    if (ammoLeft <= 0){
    if(fireRate<delay){
    yield new WaitForSeconds(delay);
    } else {
    yield new WaitForSeconds(fireRate);
    }
    Reload();

    }

    }
    function FireShot () {
    if(isPrimaryWeapon){
    if(fireAnim !autoFire !burstFire){
    BroadcastMessage("singleFireAnim", fireRate);
    } else {
    BroadcastMessage("FireAnim");
    }
    } else {
    if(fireAnim !autoFire !burstFire){
    BroadcastMessage("singleSecFireAnim", fireRate);
    } else {
    BroadcastMessage("SecondaryFireAnim");
    }
    }
    if(shellEjection !this.GetComponentInChildren(aimmode).inScope)
    ejectShell();
    if(gunType == gunTypes.gun || gunType == gunTypes.melee){
    inDelay = true;
    yield new WaitForSeconds(delay);
    inDelay = false;
    for (var i=0; i<shotCount; i++) {
    FireOneBullet();
    Kickback();
    }
    } else if (gunType == gunTypes.launcher){
    inDelay = true;
    yield new WaitForSeconds(delay);
    inDelay = false;
    for (var p=0; p<projectileCount; p++) {
    FireOneProjectile();
    }
    }
    m_LastFrameShot = Time.frameCount;
    muzzleFlashOn = true;
    if(shotSpread < maxSpread)
    shotSpread = shotSpread + spreadRate;
    hitBox = false;
    }
    function FireLaser () {
    var layerMask = 1 << 8;
    layerMask = ~layerMask;
    var hit : RaycastHit;
    var direction = transform.TransformDirection(Vector3(0,0,1));

    // Did we hit anything?
    if (Physics.Raycast (transform.position, direction, hit, laserRange, layerMask)) {
    // Apply a force to the rigidbody we hit information
    var hitRotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
    var hitInfo = new Array(hit.point, hitRotation, hit.transform, hit.normal);
    if (hit.rigidbody)
    hit.rigidbody.AddForceAtPosition(force * direction, hit.point);

    // Place the particle system for spawing out of place where we hit the surface!
    // And spawn a couple of particles
    if (hitParticles) {
    hitParticles.transform.position = hit.point;
    hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
    hitParticles.Emit();
    }

    // Send a damage message to the hit object
    hit.collider.SendMessageUpwards("ApplyDamage", damagePerSecond*Time.deltaTime, SendMessageOptions.DontRequireReceiver);
    hit.collider.SendMessageUpwards("accuracy", SendMessageOptions.DontRequireReceiver);
    //And send a message to the DecalManager
    hit.collider.SendMessageUpwards("ApplyLaserDecal", hitInfo, SendMessageOptions.DontRequireReceiver);
    }
    if(laserGFX != null){
    laserGFX.active = true;
    laserGFX.GetComponent(LineRenderer).enabled = true;
    if (audio !audio.isPlaying) {
    audio.loop = true;
    audio.Play();
    }
    var laserPoint = Vector3(0,0, Mathf.Abs(Vector3.Distance(laserGFX.transform.position , hit.point) + 1));
    laserGFX.GetComponent(LineRenderer).SetPosition(1 , laserPoint);
    }
    Kickback();
    }

    function FireOneProjectile () {
    //if(isPrimaryWeapon){
    // BroadcastMessage("FireAnim");
    //} else {
    // BroadcastMessage("SecondaryFireAnim");

    //}

    var direction = SprayDirection();

    if(launchPosition != null){
    var instantiatedProjectile1 : Rigidbody = Instantiate (projectile, launchPosition.transform.position, mainCam.transform.rotation);
    } else {
    var instantiatedProjectile : Rigidbody = Instantiate (projectile, transform.position, mainCam.transform.rotation);
    }

    if(launchPosition != null){
    instantiatedProjectile1.velocity = transform.TransformDirection(Vector3 (0, 0, initialSpeed));
    Physics.IgnoreCollision(instantiatedProjectile1.collider, transform.root.collider);
    Physics.IgnoreCollision(instantiatedProjectile1.collider, gameObject.FindWithTag("Player").transform.root.collider);

    } else {
    instantiatedProjectile.velocity = transform.TransformDirection(Vector3 (0, 0, initialSpeed));
    Physics.IgnoreCollision(instantiatedProjectile.collider, transform.root.collider);
    Physics.IgnoreCollision(instantiatedProjectile.collider, gameObject.FindWithTag("Player").transform.collider);

    }

    Kickback();
    }

    function FireOneBullet () {
    var penetrate : boolean = true;
    var pVal : int = penetrateVal;
    var layerMask = 1<<8 + 1<<2;
    layerMask = ~layerMask;
    var hits : RaycastHit[];
    var direction = SprayDirection();
    hits = Physics.RaycastAll (transform.position, direction, range, layerMask);
    System.Array.Sort(hits, Comparison);
    // Did we hit anything?
    for (var i=0;i<hits.length;i++){
    var hit : RaycastHit = hits;
    var BP : BulletPenetration = hit.transform.GetComponent("BulletPenetration");
    if(penetrate){
    if(BP == null){
    penetrate = false;
    } else {
    if(pVal < BP.penetrateValue){
    penetrate = false;
    } else {
    pVal -= BP.penetrateValue;
    }
    }
    //The DecalManager needs two bits of information
    var hitRotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
    var hitInfo = new Array(hit.point, hitRotation, hit.transform, hit.normal);
    // Apply a force to the rigidbody we hit
    if (hit.rigidbody)
    hit.rigidbody.AddForceAtPosition(force * direction, hit.point);

    // Place the particle system for spawing out of place where we hit the surface!
    // And spawn a couple of particles
    if (hitParticles) {
    hitParticles.transform.position = hit.point;
    hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
    hitParticles.Emit();
    }


    // // Send a damage message to the hit object
    hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
    hit.collider.SendMessageUpwards("accuracy", SendMessageOptions.DontRequireReceiver);
    //And send a message to the decal manager
    hit.collider.SendMessageUpwards("ApplyDecal", hitInfo, SendMessageOptions.DontRequireReceiver);

    }
    }

    }
    function Comparison(x : RaycastHit, y : RaycastHit) : int {
    var xDistance = x.distance;
    var yDistance = y.distance;
    return xDistance - yDistance;
    }
    function SprayDirection() {
    var vx = (1 - 2 * Random.value) * actualSpread;
    var vy = (1 - 2 * Random.value) * actualSpread;
    var vz = 1.0;
    return mainCam.transform.TransformDirection(Vector3(vx,vy,vz));

    }
    function Reload () {
    if(ammoLeft >= ammoPerClip || clips <= 0 || !gunActive){
    return;
    }
    if(progressiveReload){
    ProgReload();
    return;
    }
    if(!reloading){
    //if ((ammoType == ammoTypes.byClip ammoLeft < ammoPerClip clips > 0 gunActive) || (ammoType == ammoTypes.byBullet ammoLeft < ammoPerClip clips > 0 gunActive)){
    aim1.canSwitchWeaponAim = false;
    if(aim1.aim){
    aim1.aim = false;
    aim = true;
    }
    reloading=true;
    if(secondaryWeapon != null){
    secondaryWeapon.reloading = true;
    } else if(!isPrimaryWeapon){
    primaryWeapon.reloading = true;
    }
    yield WaitForSeconds(waitforReload);
    if(isPrimaryWeapon){
    BroadcastMessage("ReloadAnim", reloadTime);
    } else {
    BroadcastMessage("SecondaryReloadAnim", reloadTime);
    }

    // Wait for reload time first - then add more bullets!
    yield WaitForSeconds(reloadTime);
    reloading = false;
    if(secondaryWeapon != null){
    secondaryWeapon.reloading = false;
    } else if(!isPrimaryWeapon){
    primaryWeapon.reloading = false;
    }
    // We have a clip left reload
    if(ammoType == ammoTypes.byClip){
    if (clips > 0) {
    if(!infiniteAmmo)
    clips--;
    ammoLeft = ammoPerClip;
    }
    } else if (ammoType == ammoTypes.byBullet){
    if(clips > 0){
    if(clips > ammoPerClip){
    clips -= ammoPerClip - ammoLeft;
    ammoLeft = ammoPerClip;
    } else {
    ammoVal = Mathf.Clamp(ammoPerClip, clips, ammoLeft+clips);
    clips -= (ammoVal - ammoLeft);
    ammoLeft = ammoVal;
    }
    }
    }
    if(aim)
    aim1.aim = true;
    aim1.canSwitchWeaponAim = true;
    SendMessage("updateAmmo", ammoLeft, SendMessageOptions.DontRequireReceiver);
    SendMessage("updateClips", clips, SendMessageOptions.DontRequireReceiver);
    //}
    ApplyToSharedAmmo();

    }
    }
    function ProgReload (){
    if(reloading)
    return;
    aim1.canSwitchWeaponAim = false;
    if(aim1.aim){
    aim1.aim = false;
    aim = true;
    }

    BroadcastMessage("ReloadIn", reloadInTime);
    yield WaitForSeconds(reloadInTime);
    progressiveReloading = true;
    reloading=true;
    if(secondaryWeapon != null secondaryWeapon.secondaryFire !secondaryWeapon.secondaryInterrupt){
    secondaryWeapon.reloading = true;
    } else if(secondaryFire !secondaryInterrupt !isPrimaryWeapon){
    primaryWeapon.reloading = false;
    }

    }
    function GetBulletsLeft () {
    return ammoLeft;
    }
    function selectWeapon () {
    AlignToSharedAmmo();

    var aim1 : aimmode = GetComponentInChildren(aimmode);

    if(!isPrimaryWeapon)
    return;

    var gos = GetComponentsInChildren(Renderer);
    for( var go : Renderer in gos){
    if (go.name != "muzzle_flash")
    go.enabled=true;
    }
    if(secondaryWeapon != null){
    secondaryWeapon.gunActive = false;
    secondaryWeapon.secondaryActive = false;
    BroadcastMessage("aimPrimary", SendMessageOptions.DontRequireReceiver);
    }
    if(!takingOut !gunActive){
    aim1.canSwitchWeaponAim = false;
    BroadcastMessage("TakeOutAnim");
    takingOut = true;
    // gunActive=false;
    yield WaitForSeconds(.6);
    gunActive=true;
    takingOut = false;
    aim1.canSwitchWeaponAim = true;
    }


    }
    function deselectWeapon () {
    gunActive=false;
    var gos = GetComponentsInChildren(Renderer);
    for( var go : Renderer in gos){
    go.enabled=false;

    }

    }function walkSway () {
    if(swayTarget == 1){
    if (Vector3.Distance(transform.localPosition, walkSway1) >= .01){
    curVect= walkSway1 - transform.localPosition;
    transform.Translate(curVect*Time.deltaTime*swayRate*player.GetComponent("FPSWalkerDB").speed,Space.Self);
    } else {
    swayTarget = 2;
    }
    } else if(swayTarget == 2) {
    if (Vector3.Distance(transform.localPosition, walkSway2) >= .01){
    curVect= walkSway2 - transform.localPosition;
    transform.Translate(curVect*Time.deltaTime*swayRate*player.GetComponent("FPSWalkerDB").speed,Space.Self);
    } else {
    swayTarget = 1;
    }
    }
    }

    function defineSwayPoints () {
    walkSway1 = transform.localPosition + swayFactor;
    walkSway2 = transform.localPosition - swayFactor;
    }

    function resetPosition () {
    if (transform.localPosition != startPosition){
    curVect= startPosition - transform.localPosition;
    transform.Translate(curVect*Time.deltaTime*2,Space.Self);
    }
    }

    function sprinting () {
    areSprinting = true;
    }
    function normalSpeed () {
    areSprinting = false;
    if(secondaryWeapon != null){
    if(isPrimaryWeapon secondaryWeapon.secondaryActive)
    return;
    }
    if(!isPrimaryWeapon !secondaryActive)
    return;

    gunActive = true;
    }
    function Kickback () {
    mainCam.GetComponent("MouseLook").offsetY = kickbackAngle;
    weaponCam.GetComponent("MouseLook").offsetY = kickbackAngle;
    }

    function KickbackZ () {
    startKickback = true;
    walkSway1 = Vector3( walkSway1.x, walkSway1.y, (walkSway1.z - kickbackZ));
    walkSway2 = Vector3( walkSway2.x, walkSway2.y, (walkSway2.z - kickbackZ));
    startPosition = Vector3( startPosition.x, startPosition.y, (startPosition.z - kickbackZ));

    }

    function ceaseFiring () {
    walkSway1 = Vector3( walkSway1.x, walkSway1.y, (walkSway1.z + kickbackZ));
    walkSway2 = Vector3( walkSway2.x, walkSway2.y, (walkSway2.z + kickbackZ));
    startPosition = Vector3( startPosition.x, startPosition.y, (startPosition.z + kickbackZ));
    startKickback = false;
    }
    function activateSecondary () {
    if(secondaryWeapon == null || secondaryWeapon.secondaryFire)
    return;
    AlignToSharedAmmo();

    if(gunActive){
    gunActive = false;
    secondaryWeapon.gunActive = true;
    secondaryWeapon.secondaryActive = true;
    SendMessage("updateAmmo", secondaryWeapon.ammoLeft, SendMessageOptions.DontRequireReceiver);
    SendMessage("updateClips", secondaryWeapon.clips, SendMessageOptions.DontRequireReceiver);
    BroadcastMessage("aimSecondary", SendMessageOptions.DontRequireReceiver);

    }
    }
    function activatePrimary () {
    AlignToSharedAmmo();
    if(!gunActive){
    gunActive = true;
    secondaryWeapon.gunActive = false;
    secondaryWeapon.secondaryActive = false;
    SendMessage("updateAmmo", ammoLeft, SendMessageOptions.DontRequireReceiver);
    SendMessage("updateClips", clips, SendMessageOptions.DontRequireReceiver);
    BroadcastMessage("aimPrimary", SendMessageOptions.DontRequireReceiver);

    }
    }
    function ejectShell () {
    var instantiatedProjectile1 = Instantiate (shell, ejectorPosition.transform.position, ejectorPosition.transform.rotation);
    instantiatedProjectile1.transform.parent = ejectorPosition.transform;
    }
     
    Last edited: Apr 16, 2013
  9. chiblue3D

    chiblue3D

    Joined:
    Apr 25, 2012
    Posts:
    19
    Your problem is that the getcomponent is not finding the class, I would suggest using colliders to perform the proximity check, this way you can get get the player controller that collides with the collider around the pickup and from that find the weapon what should get the ammo. This works very well using the OnTriggerEnter and OnTriggerExit which passes the collider that hit the object.

    Add colliders to your pickup, then in your player controller scipt add the ontrigger functions, then simply test that the collider you hit is a ammo pickup, in my case I used weapon, ammo and health using the same technique.