2D Toolkit Forum
2D Toolkit => Support => Topic started by: Ben 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 () {
}
}
-
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?
-
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?
-
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.
-
Ok, I will. Thank you for pointing me at the right direction.