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: Object reference not set to an instance of an object

Discussion in 'Scripting' started by doukisan, Dec 26, 2015.

  1. doukisan

    doukisan

    Joined:
    Nov 26, 2015
    Posts:
    15
    Hello folks!

    I've searched lots of similar cases, but unfortunately none of the solutions would seem to help me.

    Well, all I want to do is instantiate a smoke effect prefab when my object is colliding with a trigger wall, so I wrote this:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class pickStarController : MonoBehaviour {
    5.  
    6.     public SpriteRenderer smokeEffect; //The Prefab
    7.  
    8.     void OnTriggerEnter(Collider other){
    9.         if (other.gameObject.tag == "WallBounds") {
    10.             SpriteRenderer smokeColor = Instantiate(smokeEffect, this.transform.position, Quaternion.Euler (new Vector3(0, 0, 90))) as SpriteRenderer;
    11.             smokeColor.color = Color.red;  
    12.         }
    13.     }
    14. }
    As you can see, I'm trying to instantiate as a SpriteRenderer type so I can change the color of the object after instantiated, but I'm getting this error after the object is created ingame:
    So you guys are my last hope, because I don't want to have to create and attach a new script to the prefab, since I can quickly edit it right after the instantiate process...
    Thank you very much for your attention and help.
     
  2. The-Little-Guy

    The-Little-Guy

    Joined:
    Aug 1, 2012
    Posts:
    297
    I believe you need to instantiate the object as a gameObject then get its component like this:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class pickStarController : MonoBehaviour {
    4.     public GameObject smokeEffect; //The Prefab
    5.     void OnTriggerEnter(Collider other){
    6.         if (other.gameObject.tag == "WallBounds") {
    7.             GameObject smokeColor = Instantiate(smokeEffect, this.transform.position, Quaternion.Euler (new Vector3(0, 0, 90))) as GameObject;
    8.             smokeColor.GetComponent<SpriteRenderer>().color = Color.red;
    9.         }
    10.     }
    11. }
     
  3. doukisan

    doukisan

    Joined:
    Nov 26, 2015
    Posts:
    15
    I already tried, I still get the message =/