Home > Enterprise >  Instantiate and Destroy a Prefab
Instantiate and Destroy a Prefab

Time:09-27

i need a help. I created a script that spawn a simple gameObject at the mouse position. This gameObject is a prefab. Since i need it to move and then destroy once it is out of the screen, this is the script i created:

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class foodManager : MonoBehaviour
{
    public GameObject food;
    

    private void Start()
    {
        
    }
    void Update()
    {

        Vector2 mousePos = Input.mousePosition;

        Vector2 objPos = Camera.main.ScreenToWorldPoint(mousePos);

        food.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -3);

        if (Input.GetMouseButtonDown(0))
        {
           food = Instantiate(food, objPos, Quaternion.identity) as GameObject;
        }

        if (food.transform.position.y < -5f)
        {
            Destroy(food);
        }

    }
}

Once i start the game, i can't instantiate the prefab. I only can if the prefab is already in the scene, and once it gets destroyed, i cant anymore. Can you guys help me if you understand where's the problem? Thanks in advice!

CodePudding user response:

First of all you are replacing the food prefab in your script. So it will only be able to be instantiated once. Seperate that into two different variables.

public class foodManager : MonoBehaviour
{
    public GameObject foodPrefab;
    public Transform food;
    
    void Update()
    {
        HandleSpawning();
        HandleDestroyingFood();
    }
    
    void HandleSpawning()
    {
        // Only allow one Food to be instantiated at a time.
        if (food != null) return;
        
        if (Input.GetMouseButtonDown(0))
        {
            Vector2 mousePos = Input.mousePosition;
            Vector2 objPos = Camera.main.ScreenToWorldPoint(mousePos);
            GameObject newFood = Instantiate(food, objPos, Quaternion.identity) as GameObject;
            food = newFood.transform;
        }
    }
    
    void HandleDestroyingFood()
    {
        if (food.position.y < -5f)
        {
            Destroy(food);
        }
    }
}

CodePudding user response:

if (Input.GetMouseButtonDown(0))
    {
       food = Instantiate(food, objPos, Quaternion.identity) as GameObject;
    }

this Line is the main problem as you are overwriting the prefab with a new Instantiated object

In the starting, you are using the food variable to be the prefab and after the Instantiate, you overwrite it with the new game object which is not the prefab

public GameObject food; I'm assuming this line is for the Prefab you drag in the editor

So, to solve this Make a new variable to hold the Instantiated Object. Not the food variable you use for the Prefab.

  • Related