- Home /
The problem was fixed by creating a prefab from the asset
How to add an asset to a script-enabled public game object?
I'm following a tutorial that was created for Unity 4.6, and am up to a point where we are instantiating prefabs at runtime. The prefab to be created is added to the Inspector in Unity, with the codes public GameObject enemyPrefab
and Instantiate (enemyPrefab, new Vector3 (0, 0, 0), Quaternion.identity);
.The problem is that, with this being a GameObject, I'm unable to instantiate by using this unless an instance is already in the Hierarchy. So how do I add an asset to the position in the Inspector without adding it to the Hierarchy first?
That's a little confusing. By GameObject already in the scene you mean the one the script with your two code snippets is attached to? If so, of course it needs to be in the scene, otherwise it won't execute. But the code does not have to be on the prefab you want to instantiate as well. Usually you have two gameobjects, one in the scene with spawn code and one as a prefab referenced for instantiation.
Sorry for the confusion. The script is attached to an empty game object that is in the hierarchy. The problem I have is that I can't add a prefab to it that I want to load at the start of the level unless an instance of the prefab is already in the hierarchy. To be clear, the reason I don't just add the object without a script is because this will be used to spawn and manage multiple of the same object.
Sorry for the trouble, the asset just wasn't being accepted as a prefab n.n'
Answer by Light_ · Oct 27, 2016 at 03:08 AM
I think what Hex is getting at ^^ Put your script that calls the object to instantiate on an empty gameobject in the scene. Even if it has no renderer, something like a "gamemanager". Then use it to call the "instantiate(enemyPrefab) once the scene starts. If you're trying to "create an object from an instance" put a blank copy of your prefab with no renderer in the scene and see if that solves your problem?
I have an empty gameobject with the script attached, as suggested. Adding a blank copy to the scene does work, but, in the tutorial, the asset itself was added directly to the script by dragging the asset into the inspector of the empty gameobject, and that's what I am trying to replicate.
Sorry for the trouble, the asset just wasn't being accepted as a prefab n.n'
Follow this Question
Related Questions
How to destroy all gameobjects active in hierarchy? 1 Answer
Instantiated Object being auto-deleted 0 Answers
How to instantiate within GameObject 1 Answer
Unity not Instantiating as Prefab 1 Answer