Search Unity

  1. Unity 2019.1 is now released.
    Dismiss Notice

null reference in instantiate

Discussion in 'Scripting' started by roblin, May 1, 2009.

  1. roblin

    roblin

    Joined:
    May 1, 2009
    Posts:
    14
    i want to make a script that creates a new playercharacter when they land on a plane below the playarea, but when i try to refere to the playercharacterprefab
    it gives the nullreference error message, any guess to why?
    the script is below

    var playerprefab : GameObject;
    function OnCollisionEnter(){
    Instantiate(playerprefab, Vector3.zero, Quaternion.identity);
    }

    im kind of a noob so i hope theres something really trivial that i never understood about instantiate or something like that. and if it is, please tell me.

    ... really, please do.
     
  2. Tempest

    Tempest

    Joined:
    Dec 10, 2008
    Posts:
    1,286
    You're not pointing to a prefab with this:

    Code (csharp):
    1. var playerprefab : GameObject;
    You're just creating a variable which is a GameObject type, but has no value, and then trying to instantiate it.

    Try doing this:


    Code (csharp):
    1. public var playerprefab : GameObject;
    Now the playerprefab variable will show up in the Inspector where this script is located. You can drag your player prefab from your Project folder and link it to this variable, so the script knows which prefab to spawn.[/code]
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,050
    "Public" is unnecessary. Javascript variables are public by default unless you specify "private".

    --Eric
     
  4. roblin

    roblin

    Joined:
    May 1, 2009
    Posts:
    14
    that worked, thx for helping