Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

NullReferenceException C#

Discussion in 'Scripting' started by gornex, Jul 3, 2015.

  1. gornex

    gornex

    Joined:
    Jul 3, 2015
    Posts:
    3
    I wanted to make object the script is attached to, to be parent of instantiated in Update() MemoryScript objects.

    The error I get is:
    MemoriesManagerScript.cs

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class MemoriesManagerScript : MonoBehaviour {
    5.  
    6.     public MemoryScript memory;
    7.     private System.Random r = new System.Random();
    8.     // Use this for initialization
    9.     void Start () {
    10.     }
    11.    
    12.     // Update is called once per frame
    13.     void Update () {
    14.         //Debug.Log (transform == null);
    15.         if (System.DateTime.Now.Second % 5 == 0) {
    16.             (Instantiate (memory, new Vector3 (r.Next (99) - 43, r.Next (26) - 4, 0), Quaternion.identity) as GameObject).transform.parent = gameObject.transform;
    17.         }
    18.     }
    19. }
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    why are you using the system random and not unity's Random class?

    have you dragged something into the "memory" slot in the inspector?

    break line 16 down into it's parts rather than trying to chain it all together. It'll help identify which bit is going wrong.


    oh and
    Code (csharp):
    1.  
    2. gameObject.transform;
    3.  
    is a little redundant, you can just use
    Code (csharp):
    1.  
    2. transform;
    3.  
    to reference the current gameobject's transform
     
  3. gornex

    gornex

    Joined:
    Jul 3, 2015
    Posts:
    3
    I have dragged prefab of Memory object which has attached MemoryScript to it. About change in code you have written, thanks.
    I had tried before i posted here something like this:

    Code (CSharp):
    1. GameObject go = (GameObject)Instantiate (memory, new Vector3 (r.Next (99) - 43, r.Next (26) - 4, 0), Quaternion.identity)
    2. go.transform.parent = gameObject.transform;
    But it gave me same error in console.
     
  4. Nikussan

    Nikussan

    Joined:
    Jan 23, 2014
    Posts:
    5
    Instantiate(...) returns instance of supplied object, if you supply a component/behavior - you receive it, not a GameObject
    So casting the result to GameObject using as keyword returns null and you receive NullReferenceException
    Cast it to type of prefab you provide, and then get gameObject/transform from it
     
    gornex likes this.
  5. gornex

    gornex

    Joined:
    Jul 3, 2015
    Posts:
    3
    @Nikussan Thanks for explanation, now it works like I wanted :)