Unity | instantiate only works once

Viewed 59

For some reason whenever I Instantiate, I can only instantiate once per build/run/game. I've tried to see if it was that I could only use different prefabs, but that isn't it. Please help, I've been trying to find an answer but no one seems to have the same problem. Thanks for reading this.

heres the project (assets and project settings) if you wanna mess around with it yourself

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CreatePipe : MonoBehaviour
{
    public GameObject Pipe;
    public bool yes = false;
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine("initializationn");
        Debug.Log("started");
    }

    // Update is called once per frame
    void Update()
    {
        // if (yes){
        //     inst();
        //     yes = false;
        // }
        
    }

    public IEnumerator initializationn()
    {
        
        Debug.Log("started");
        inst();
        // yes = true;
        yield return new WaitForSeconds(3);
        inst();
        // yes = true;
        yield return new WaitForSeconds(3);
        inst();
        // yes = true;
        yield return new WaitForSeconds(3);

        // while (true){
        //     inst()
        //     yield return new WaitForSeconds(3);
        // }
    
    }
    public void inst(){
        Debug.Log("in");
        var g  = Instantiate(Pipe, new Vector3(7f, Random.Range(-6.5f,0f), 0f), Quaternion.identity);
        g.SetActive(true);
        g.name = "Pipe";
    }
    
}
2 Answers

The reason only one pipe exist at at time is that the script "PipeStuff" you attached to the Prefab "Pipe", makes it a singleton. So every time you create a duplicate instance you are deleting that object since a "PipeStuff" already exist.

enter image description here

Suggestions:

Your script is absolutely fine there is no problem with it but perhaps you are destroying that gameObject which is intantiating those pipe prefabs thats why its not working as you intend it to, any ways check if it is so because there seems to be no other problem with your script and also you can do it in one more way by using invokeRepeating function too like:


    InvokeRepeating( nameof(inst), 0, 3 );

it will call this function repeatadely after every 3 seconds and the first parameter which is 0, is used for delay at the start so if you want to Invoke that function after some seconds you can do so as well and when you are done you can destroy or disable that gameObject too, its just a basic way of doing so otherwise there are tons of ways to do so anyways...

Hope it helps... Happy Coding :)

Related