Search Unity

Instantiate from script

Discussion in 'Scripting' started by Lka, Aug 6, 2006.

  1. Lka

    Lka

    Joined:
    Aug 6, 2006
    Posts:
    297
    Hi
    I'd like to know if it's possible to instatiate a gameobject from mono script even if it's not present in the "Hierarchy" panel but only as a prefab ("Project" panel).

    I need to instantiate it using the object name, loaded from text file.

    UnityEngine.GameObject wob = UnityEngine.GameObject.Find(words[5]);
    if (wob == null)
    Debug.Log("GameObject.Find error " + words[5]);
    UnityEngine.GameObject obj = Instantiate(wob) as UnityEngine.GameObject;
    if (obj == null)
    Debug.Log("Instantiate error " + wob.name);

    where 'words' is a string array and words[5] contains the object name.
    This script is called from a MonoBehaviour inherited class.

    Thanks
    Lka
     
  2. jeremyace

    jeremyace

    Joined:
    Oct 12, 2005
    Posts:
    1,661
    Yes and no. You can only use the Find() functions when the object is present in the scene. You can set up public GameObject variables in your script and drag your prefabs to that without having them in the scene. You would need a variable for each one or a public array.

    Unfortunately there is no way in Unity to load an object just by name like that. It has to do with the way Unity cleans up unused objects when you build a game. If an object is loaded from code, there is no way Unity can know if it is used or not.

    -Jeremy
     
  3. Lka

    Lka

    Joined:
    Aug 6, 2006
    Posts:
    297
    OK.. I'll put a copy of all objects that can be instantiated by the script in a hidden place in the level.

    Thanks
    Lka
     
  4. Morgan

    Morgan

    Joined:
    May 21, 2006
    Posts:
    1,223
    They don't need to be in the level literally--as long as you have dragged them to GameObject variable(s) in the inspector, as Jeremy describes.