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. Dismiss Notice

NullReferenceException message, can't figure out why??

Discussion in 'Scripting' started by Lmaryon, Jul 15, 2014.

  1. Lmaryon

    Lmaryon

    Joined:
    Jul 15, 2014
    Posts:
    18
    Hi, i'm very new to unity and Csharp. I've been following a tutorial on Youtube to create an endless runner game. I've got near to the end but hit this hurdle.

    usingUnityEngine;
    usingSystem.Collections;

    publicclassSpawnHandler : MonoBehaviour {

    publicGameObject[] stageCollection;

    voidOnTriggerEnter2D(Collider2Dother)
    {
    if (other.gameObject.tag == "SpawnTrigger")
    {
    varstage = other.gameObject;
    TransformspawnLocation = stage.transform.parent.Find("SpawnLocation");

    GameObject obj = Instantiate(stageCollection[Random.Range(0, stageCollection.Length)], <--- this is the line
    spawnLocation.position,
    Quaternion.identity) asGameObject;

    obj.name = "SpawnedStage";
    }

    if (other.gameObject.name == "SpawnLocation")
    {
    Destroy(other.gameObject.transform.parent.gameObject);
    }
    }
    }


    any help would be great, thanks!! this is the link to the tutorial

    the bit i'm stuck on starts at 35:50.
     
  2. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    Have you assigned anything into stagecollection?
     
    Lmaryon likes this.
  3. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
  4. Lmaryon

    Lmaryon

    Joined:
    Jul 15, 2014
    Posts:
    18
    yes I have, a prefab
     
  5. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    Are you certain that there is always a GameObject named "SpawnLocation" at the same level of hierarchy as the GameObject that collided?

    A.K.A are you certain that spawnLocation always has a value?
     
    Lmaryon likes this.
  6. Lmaryon

    Lmaryon

    Joined:
    Jul 15, 2014
    Posts:
    18
    not sure, could you explain how I could check? sorry very new to this..
     
  7. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,738
    Just before the line giving you an error, insert:
    Code (csharp):
    1. Debug.Log("Spawn location? " + (spawnLocation != null ? "Exists!" : "Doesn't exist!") );
    In the console just before the error, this will let you know whether spawnLocation exists or not.
     
    Lmaryon likes this.
  8. Lmaryon

    Lmaryon

    Joined:
    Jul 15, 2014
    Posts:
    18
    Thanks very much, I'll try that. Thanks for your help :)