Hello Guest

Author Topic: How to instantiate a prefab  (Read 4279 times)

indy2005

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 19
    • View Profile
How to instantiate a prefab
« 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

profanicus

  • 2D Toolkit
  • Full Member
  • *
  • Posts: 167
    • View Profile
Re: How to instantiate a prefab
« Reply #1 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.

guanqun

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 3
    • View Profile
Re: How to instantiate a prefab
« Reply #2 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