GameObject isn't instantiated... [Beginner] [Resolved]

GameObject gameObject = GameObject.Instantiate(prefab, GameObject.Find(“Canvas”).transform);

where prefab is set as a suitably created Prefab, and Canvas is in the Scene.

But it doesn’t create any object…

I would really appreciate any help.


Sorry for edit

-Update-

I want to instantiate 11 GameObject Instances at once.
Data is stored at InitData instances.

[System.Serializable]
public class InitData
{
    public GameObject prefab;

    public Sprite sprite;
    public Vector3 position;
    public Vector2 sizeDelta;
    public Vector3 scale;
    public Quaternion rotation; // these should be protected or, initiated using InitData.ctor()

    public virtual GameObject InitGO() { return null; }

    public override bool Equals(object obj)
    {
        if (obj is InitData)
        {
            InitData id = (InitData)obj;

            return id.prefab == prefab && id.position == position && id.sizeDelta == sizeDelta && id.scale == scale && id.rotation.x == rotation.x && id.rotation.y == rotation.y && id.rotation.z == rotation.z && id.rotation.w == rotation.w;
        }
        else
        {
            return false;
        }
    }
}


InitDataUI inherits InitData

public class InitDataUI : InitData
{

    public InitDataUI(GameObject gameObject, GameObject prefab)
    {
        this.prefab = prefab;

        Image image = gameObject.GetComponent<Image>();
        RectTransform rectTransform = gameObject.GetComponent<RectTransform>();

        sprite = image.sprite;
        position = rectTransform.position;
        sizeDelta = rectTransform.sizeDelta;
        scale = rectTransform.localScale;
        rotation = rectTransform.rotation;

    }

    public override GameObject InitGO()
    {
        GameObject gameObject = GameObject.Instantiate(prefab, GameObject.Find("Canvas").transform);
        Image image = gameObject.GetComponent<Image>();
        RectTransform rectTransform = gameObject.GetComponent<RectTransform>();

        image.sprite = sprite;
        rectTransform.position = position;
        rectTransform.sizeDelta = sizeDelta;
        rectTransform.localScale = scale;
        rectTransform.rotation = rotation;

        return gameObject;

    }
}


Then ObjectInit.Init calls InitData.InitGO

public class ObjectsInit : Manager
{
	public ListStringDictionary<InitData> initDatas;
    public void Start()
    {
        
    }

    public List<GameObject> Init(string name)
    {
        List<GameObject> retur = new();

        List<InitData> ID = initDatas[name];
        foreach (InitData data in ID)
        {
            retur.Add(data.InitGO());
        }

        return retur;
    }
}


ObjectInit.Init is called by SceneSettings.Start

public class SceneSettings : Manager // 100 ExcOrder
{
    public void Start()
    {
        blocksG = new(new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, Get<ObjectsInit>().Init("BlocksG"));
        blocksR = new(new List<int> { 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 }, Get<ObjectsInit>().Init("BlocksR"));
    }
}


Manager inherits MonoBehaviour
SceneSettings.Get returns Manager instance of type T
ObjectInit, SceneSettings are components attached to Managers
SceneSettings has Excution Order +100

But GameObject is not instantiated still…


-Update 2-
In addition, I have more than 50 GameObjects loaded each game.
So, I’m gonna use ObjectPool to instantiate these objects…

Don’t do this:

Remember the first rule of GameObject.Find():

Do not use GameObject.Find();

More information: Regarding GameObject.Find · UnityTipsRedux

In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.

If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way™ success of accessing things in your game.

“Stop playing ‘Where’s GameWaldo’ and drag it in already!”

Here’s why all this stuff is CRAZY code:

Once you have fixed that problem, if it still doesn’t work…

Sounds like you wrote a bug… and that means… time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

Remember with Unity the code is only a tiny fraction of the problem space. Everything asset- and scene- wise must also be set up correctly to match the associated code and its assumptions.

1 Like

Does it log an error to the console? Because if not, it will create the object. You probably are just looking in the wrong place to see it, eg what Kurt mentioned in case you have multiple objects in the scene named “Canvas”.

Also, you don’t code Canvas GUI this way. Instead, your whole canvas contains everything that you may need at any given time. Then just SetActive(false) what isn’t currently needed.

And also, don’t use UGUI. We have UI Toolkit which for beginners is much easier than wrapping your head around canvases, scalers, layouters, and so forth.

It’s not clear what goes wrong, or where.

Have you tried to simply debug your code to see what it actually does while it executes?

I made some mistakes :

[Serializable]
public class PrefabHelper : EditorWindow
{
    private List<Transform> positions;
    private List<RectTransform> Rectpositions;
    private string name = "";
    private string nameDict = "";
    private GameObject prefab;
    private List<GameObject> go;
    private ListStringDictionary<InitData> IDS = new();
    private DictInitDataSO lids;
    private SerializedProperty SP;
    private int mode = 0;
    private int number;
    private Vector2 Scrollpos = new();
    private string log = "";
    private string method = "";
    List<InitData> list;


    private void Update()
    {
        positions = new List<Transform>();
        Rectpositions = new List<RectTransform>();
        foreach (GameObject gameObject in Selection.gameObjects)
        {
            positions.Add(gameObject.transform);

            RectTransform rect = gameObject.GetComponent<RectTransform>();
            if (rect != null)
            {
                Rectpositions.Add(rect);
            }
        }
    }

    private void OnGUI()
    {
        EditorGUILayout.BeginVertical("Box");
        {
            try
            {
                Scrollpos = EditorGUILayout.BeginScrollView(Scrollpos, GUILayout.Height(position.height - 15));
                if (mode == 0)
                {
                    go = Selection.gameObjects.ToList();
                    number = go.Count;
                    prefab = (GameObject)Resources.Load(name);

                    EditorGUILayout.LabelField($"Number of selected gameObjects : {number}");
                    EditorGUILayout.LabelField($"Number of InitDatas : {IDS.Count}");

                    name = EditorGUILayout.TextField("Prefab", name);
                    nameDict = EditorGUILayout.TextField("name in Dict", nameDict);

                    if (GUILayout.Button(new GUIContent("Prefab(2D)")))
                    {
                        list = new();
                        foreach (GameObject go in go)
                        {
                            Console.WriteLine("fnkiwefjl.wvkgjreg");
                            list.Add(new InitData2D(go, prefab));
                        }

                        IDS.Add(nameDict, list);
                    }

                    if (GUILayout.Button(new GUIContent("Prefab(UI)")))
                    {
                        list = new();
                        foreach (GameObject go in go)
                        {
                            Console.WriteLine("fnkiwefjl.wvkgjreg");
                            list.Add(new InitDataUI(go, prefab));
                        }

                        IDS.Add(nameDict, list);
                    }

                    if (GUILayout.Button(new GUIContent("Prefab(UI, Other)")))
                    {
                        list = new();
                        foreach (GameObject go in go)
                        {
                            Console.WriteLine("fnkiwefjl.wvkgjreg");
                            list.Add(new InitDataOtherUI(go, prefab));
                        }

                        IDS.Add(nameDict, list);
                    }

                    if (GUILayout.Button(new GUIContent("See List")))
                    {
                        mode = 1;
                    }
                }
                else
                {
                    lids = CreateInstance<DictInitDataSO>();
                    lids.data = IDS;
                    SP = new SerializedObject(lids).FindProperty("data");
                    EditorGUILayout.PropertyField(SP);
                    if (GUILayout.Button(new GUIContent("Return")))
                    {
                        mode = 0;
                    }
                }

                if (GUILayout.Button(new GUIContent("Clear")))
                {
                    IDS = new();
                }

                if (log != "")
                {
                    EditorGUILayout.Space(15f);
                    string newlog = "Error Message : \n" + log;

                    EditorGUILayout.LabelField(newlog, GUILayout.Height(newlog.Split("\n").Length * 15));
                    if (GUILayout.Button(new GUIContent("Clear Log")))
                    {
                        log = "";
                    }
                }

                EditorGUILayout.Space(15f);
                if (GUILayout.Button(new GUIContent("Exit")))
                {
                    GetWindow(typeof(PrefabHelper)).Close();
                }

                EditorGUILayout.EndScrollView();
            }
            catch (Exception e)
            {
                log = e.ToString();
            }

        }
        EditorGUILayout.EndVertical();
    }

    [MenuItem("Tools/Prefab Helper")]
    public static void ShowWindow()
    {
        var window = GetWindow(typeof(PrefabHelper));
    }
}

I used prefab helper like this and copypasted elements.

But we can copy values only from elements, so InitData.InitGO() would not be overrided.

public virtual GameObject InitGO() { return null; }

this function is called, which means InitGO() returns null

ObjectInit .Init returns a list with nulls only

No GameObject would be instantiated…

I am very happy you found your solution, it sounds like you did a really good job tracking that down. Congratulations!

1 Like