Search Unity

Error NullReferenceException

Discussion in 'Scripting' started by Mors-A-Vita, Dec 7, 2012.

  1. Mors-A-Vita

    Mors-A-Vita

    Joined:
    Dec 7, 2012
    Posts:
    8
    Hello sorry I am new to unity and having trouble instantiating a camera on button down and turning my main off then having the "newCamera" follow my "newAmmo" projectile until its destroyed or the "cameraChange" goes up Here is the code I tried again sorry I am new and don't know all the posting rules either

    #pragma strict

    static var canThrow : boolean = true;
    var throwSound : AudioClip;
    var ammoObject : Rigidbody;
    var throwForce : float;
    var arc : float;
    private var changeCamera : boolean;
    var ammoCamera : Camera;
    function Start ()
    {


    }

    function Update ()
    {

    if(Input.GetButtonUp("Fire1") canThrow)
    {
    //Script for creating Ammo projectile on mouse click down
    //Works good
    audio.PlayOneShot(throwSound);
    var newAmmo : Rigidbody = Instantiate(ammoObject,transform.position, transform.rotation);
    newAmmo.name = "Ammo";



    newAmmo.transform.Rotate(0,90,-5);
    newAmmo.rigidbody.velocity = transform.TransformDirection(Vector3(0,0, throwForce));
    Physics.IgnoreCollision(transform.root.collider,newAmmo.collider, true);

    }
    // Change camera to Ammo only on true conditions
    // changeCamera "F" button down and Ammo object is instantiated
    if(Input.GetButtonDown("changeCamera") GameObject.Find("Ammo") != null)
    {
    var newCamera = Instantiate(ammoCamera,transform.position, transform.rotation);
    newCamera.name ="ammoCamera";

    Camera.main.enabled = false;
    newCamera.enabled= true;


    newCamera.transform.parent = newAmmo.transform;

    }

    // Change Camera Back only on true conditions
    // changeCamera "F" button up and Ammo object is instantiated
    if(Input.GetButtonUp("changeCamera") GameObject.Find("Ammo") != null)
    {
    newCamera.enabled= false;
    Camera.main.enabled = true;
    }


    }
    @script RequireComponent(AudioSource)

    I get an error only when changeCamrea button is pressed and the error is on line
    newCamera.transform.parent = newAmmo.transform;

    I have a camera prefab named ammoCamera dragged and loaded I also see the ammoCamera being created in the hiearchy but still get a null reference exception I am lost again sorry I am new and don't know all the rules
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401