Tuesday, April 14, 2015

Instantiate a prefab

I keep having to look up how to instantiate a prefab.  This is an easier place for me to look for it.

Put this as a method variable

// C# 

public Transform prefabMovePath;

Once you have that method variable in your Unity script, then you will see this.
Simply drag and drop the prefab you want to the script to instantiate to the PrefabMovePath in unity.


Since I'll probably forget that too, the way you create a prefab is pretty simple, build it up in the hierarchy/scene, then drag it from the hierarchy to the project.  It will have a blue cube icon.

Use this Instantiate code to create an instance of that prefab.

private Transform curMove;
void Start() 
{
    curMove = (Transform)Instantiate(prefabMovePath, new Vector3(0, 0, 0), Quaternion.identity);
}

Then, since that prefab has a script I need access to, use this when wanting to call code in the script that prefab is attached to.

        MovePath mp = curMove.GetComponent();
        mp.rotateLeft();

No comments: