- Home /
instantiate prefabs/gameObjects
Hi, im developing a 2d game.
im using this code to invoke three different kind of objects ramdomly to the scene.
#pragma strict
var posible_col = new Array();
var col : GameObject;
function Start()
{
posible_col[0] = GameObject.Find ("f_col_1");
posible_col[1] = GameObject.Find ("f_col_2");
posible_col[2] = GameObject.Find ("f_col_3");
InvokeRepeating("next_col", 2, 3);
}
function next_col ()
{
col = posible_col[Random.Range(0,3)];
Instantiate(col, new Vector2(0 , 9), Quaternion.identity);
}
it works fine, but it does not instantiate a prefab! i can see at the inspector that the object invoked is not a prefab because the cube besides the drop-down tags option, is not blue but green, blue and red (the components of the object invoked are the same as the prefab!).
im using another script that has a OnCollisionEnter2D funtion on it, it works untill i use this one. And the tests i've made so far, show that this collision script only works when the colliders are prefabs, i dont know why, but when two of these invoked objects collide, apearly it does not detect the collision and so nothing happens.
the names i used when GameObject.Find are the names of my prefabs, ¿why it instantiate an object? ¿is there something wrong about this code i've posted, that could interfere with the other one?
thanks for your help!
First off, if you dont use a proper code block then no one can help you.
I fixed it this time but please post your code properly formatted in the future.,
Answer by Jeff-Kesselman · Jun 19, 2014 at 12:54 AM
Instantiate makes a clone of an object. This is an object that is an exact copy with all the same components and settings.
In the special case that it is given a prefab, it makes a prefab instance,
You did not give it a prefab, however. You gave it a prefab-instance from your hirearchy, which as far as it is concerned is just an object to clone.
OP responded: thank you so much!
so i must write in the code a different way to find it?
or what do i have to do?
they are in a folder called "prefabs".
You have two choices.
(1) Declare a public GameObject field in your script to hold the prefab and set it in the editor. http://docs.unity3d.com/$$anonymous$$anual/InstantiatingPrefabs.html
(2) Use Resources.Load to load the prefab from your assets. http://docs.unity3d.com/ScriptReference/Resources.Load.html
Hi againg!
i've changed all the prefabs to the Resources folder, and im now using the Resources.Load. ("prefabs/col1"); to load each one of the objects, it instantiate them without errors, but i still dont get them to be prefabs. what else i need to do?
i dont understand how to declare a public GameObject and set it to the editor, didn´t found it where you so kindly pointed.
Thanks a lot!