Hello Guest

Author Topic: Object reference not set to an instance of an object  (Read 5144 times)

Ben

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 9
    • View Profile
Object reference not set to an instance of an object
« on: May 03, 2013, 10:46:12 am »
Hi,

I'm getting the error 'Object reference not set to an instance of an object'. I've attached the following script to an empty game object, it is supposed to create a subclass of a sprite. Any help is very much appreciated.


public class Box : tk2dSprite {
   
    private tk2dSprite sprite;
   
    void Awake () {
       
        base.Awake();
       
        GameObject go = new GameObject();
        tk2dSprite sprite = go.AddComponent<tk2dSprite>();
        sprite.color = Color.red;
        sprite.scale = new Vector3(300, 300, 1);       
        sprite.Build();
    }
   
    // Use this for initialization   
    void Start () {
       
    }
   
    // Update is called once per frame
    void Update () {
   
    }
}


unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Object reference not set to an instance of an object
« Reply #1 on: May 03, 2013, 10:51:04 am »
You've created a sprite, but you haven't assigned any sprite definition to it.
What exactly are you trying to do there?
Also why is your Box class inheriting from tk2dSprite?

Ben

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 9
    • View Profile
Re: Object reference not set to an instance of an object
« Reply #2 on: May 03, 2013, 11:04:45 am »
The Box class is inheriting from tk2dSprite because I want to add additional properties and protocol to it. Simply, I'm trying to create a sprite with extended functionality. How do I assign a definition to a sprite?

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Object reference not set to an instance of an object
« Reply #3 on: May 03, 2013, 11:22:10 am »
It isn't necessary to do it like that. In Unity, you add additional monobehaviours to your component, and they can interact with other components.
So if you want to create additional behaviours to your sprite like moving it, etc, simply attach the component to the sprite and do it like that.

Normally you'd just do it in the Unity interface - create a public variable and drag a reference to it.
If you want to spawn sprites at runtime entirely from code, you should read up on resources folders and how those work in Unity - you can load SpriteCollectionData objects using Resources.Load, and then use sprite.SetSprite( collection, "name"); to assign the sprite.
Also keep in mind you can create prefabs, and load them in.


Ben

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 9
    • View Profile
Re: Object reference not set to an instance of an object
« Reply #4 on: May 03, 2013, 11:27:53 am »
Ok, I will. Thank you for pointing me at the right direction.