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

NullReferenceException Error

Discussion in 'Scripting' started by nonabonasonadona, Jan 4, 2015.

  1. nonabonasonadona

    nonabonasonadona

    Joined:
    Dec 8, 2014
    Posts:
    17
    Hi,

    I am getting the error: NullReferenceException: Object reference not set to an instance of an object.
    It occurs when I click on any 3D object while in Play.

    Code (CSharp):
    1. if (Input.GetMouseButtonDown (0))
    2.         {
    3.             Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    4.             RaycastHit hit;
    5.             if (Physics.Raycast(ray, out hit)){
    6.             Transform projectile = Instantiate(missile, new Vector3(0f,0.301f,1.158f), Quaternion.identity) as Transform;
    7.             // turn the projectile to hit.point
    8.             projectile.LookAt(hit.point);              //Error here
    9.  
    10.             // accelerate it
    11.             projectile.rigidbody.velocity = projectile.forward * 10;                //and error here also
    12.             }
    13.         }
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    if it's erroring both those lines, then its projectile that is null
    check that missile exists and has a transform
     
  3. nonabonasonadona

    nonabonasonadona

    Joined:
    Dec 8, 2014
    Posts:
    17
    Thank you, I realized missile was declared as a gameobject and not a transform...