Hello,
I can instantiate one gameobject by C# with a prefab in design mode:. I use the code of unity help to create that:
But when i want create 10 instances in one shot by a loop, only one is created.
I code the loop at any location in the code, it s a miss !
So exists it a system to create multi instance of gameobject by a prefab with only one command in a menu ?
If it s a yes answer, can you help me.
Thanks you for your help.
Your code doesn’t have any loops in it - it would be better to show us an actual attempt of a loop to help debug it.
And when you post code, copy and paste the code using code tags - it’s more readable, etc.
As a guess, though, I think the editor immediately selects the object you have created. So the second (and third, and so on) time you loop, Selection.activeObject is the object you have just spawned, which is a scene object and not a prefab, so PrefabUtility doesn’t spawn it. Maybe try storing Selection.activeObject’s value in a variable of your own before you instantiate anything, and use that as your prefab.
1 Like
Thanks for your help, I think you are right about the behaviour of the activeobject, I must lost it in the fight !
I try to keep it in a variable and use it for each loop. Thanks very much.
using UnityEngine;
using UnityEditor;
public class Example
{
[MenuItem("Examples/Instantiate Selected")]
static void InstantiatePrefab()
{
{
GameObject go = Selection.activeObject as GameObject;
for (int i = 0; i < 5; i++)
{
go = (GameObject)PrefabUtility.InstantiatePrefab(Selection.activeObject as GameObject);
go.name = "truc"+i;
}
}
}
[MenuItem("Examples/Instantiate Selected", true)]
static bool ValidateInstantiatePrefab()
{
GameObject go = Selection.activeObject as GameObject;
if (go == null) return false;
go.name = "trucMuche;";
return PrefabUtility.IsPartOfPrefabAsset(go);
}
}
And at the end, I have 5 gameobjects with the name truc1, truc2, truc3.
It"s ok. Thank you