Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Instantiating an object and giving a velocity causes NullReferenceException

Discussion in 'Editor & General Support' started by MrConkin, Apr 13, 2015.

  1. MrConkin

    MrConkin

    Joined:
    Feb 11, 2013
    Posts:
    20
    I'm trying to set the velocity of an instantiated object using the following code. However, line 22 is causing a NullReferenceException. I understand this must mean that the probe3DClone variable must be returning null, but I'm confused as to why (as far as I can tell the same code is used in the Unity documentation). How can I make this work?

    Code (csharp):
    1.  
    2.     void Update ()
    3.     {
    4.  
    5.         //When Fire1 is pressed, create a probe at launcher location
    6.         if (Input.GetButton("Fire1") && Time.time > nextFire)
    7.         {
    8.  
    9.             //Get click location of mouse
    10.             clickLocation = Input.mousePosition;
    11.             clickLocation = Camera.main.ScreenToWorldPoint(clickLocation);
    12.  
    13.             nextFire = Time.time + fireRate;
    14.  
    15.             //Variable to reference instantiated probe2D
    16.             Rigidbody probe3DClone;
    17.             //Creates probe3D at probeSpawn
    18.             probe3DClone = Instantiate (probe3D, probe3DSpawn.position, probe3DSpawn.rotation) as Rigidbody;
    19.             //Set probe3D velocity
    20.             probe3DClone.velocity = new Vector3(clickLocation.x, ySpeed, zSpeed);
    21.         }
    22.  
    23.     }
    24.  
     
  2. MrConkin

    MrConkin

    Joined:
    Feb 11, 2013
    Posts:
    20
    Figured it out. For some reason I couldn't store the instantiated object as a Rigidbody, but I could as a GameObject. Used the following:

    Code (csharp):
    1.  
    2.             //Variable to reference instantiated probe2D
    3.             GameObject probe3DClone;
    4.             //Creates probe3D at probeSpawn
    5.             probe3DClone = Instantiate (probe3D, probe3DSpawn.position, probe3DSpawn.rotation) as GameObject;
    6.  
    7.             //Set probe3D velocity
    8.             probe3DClone.GetComponent<Rigidbody>().velocity = new Vector3(clickLocation.x, ySpeed, zSpeed);
    9.