2D Toolkit Forum

2D Toolkit => Support => Topic started by: indy2005 on September 09, 2013, 10:29:12 pm

Title: How to instantiate a prefab
Post by: indy2005 on September 09, 2013, 10:29:12 pm
Hi,

How do I instantiate a tk2DSprite from a prefab.  I have an Assets/Resources/Prefabs folder in my project with an object I created as a tk2DSrite...but I am being told I am trying to instantiate a null object?

Also, do I instantiate a GameObject or a tk2DSprite object...(I am not sure if a tk2DSprite is just a component added to a normal game object and I need to use GetComponent to get the tk2DSprite from the game object....)

Code: [Select]
GameObject eggSprite = (GameObject) Instantiate(Resources.Load("Level_01_Egg"));
Any advice appreciated...I am trying to use C sharp.

Regards

Stephen
Title: Re: How to instantiate a prefab
Post by: profanicus on September 09, 2013, 11:15:24 pm
You can do it via Resources.Load or via a prefab reference in your script that you have dragged/dropped using the inspector.

Sprite is a component on a Gameobject and you won't be able to Instantiate one directly - you will need to use GetComponent if you want to access its api.

If using Resources.Load you need to include the path if it is in a subfolder, so "Prefabs/Level_01_Egg". It's returning null because it can't find the object.
Title: Re: How to instantiate a prefab
Post by: guanqun on September 10, 2013, 02:27:56 am
@profanicus is correct that the path should be relative to your Resouces folder, so in your case, it should be "Prefabs/Level_01_Egg".

HTH