Home > OS >  How can I destroy a clone of a Prefab in Unity 3D?
How can I destroy a clone of a Prefab in Unity 3D?

Time:08-10

I'm trying to make it so that a projectile, (in my case a slice of pizza) is destroyed once it travels a certain distance. I have no errors in my code and I don't know what I'm doing wrong, please help I'm fairly new to coding in Unity. (I have a comment written in the spot I need help with)

Here's my script:

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

public class PlayerController : MonoBehaviour
{
    private float horizontalInput;
    private float speed = 12.0f;
    private float leftBoundary = -10.0f;
    private float rightBoundary = 10.0f;

    public GameObject pizzaPrefab;
    private GameObject pizza;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");

        transform.Translate(Vector3.right * Time.deltaTime * speed * horizontalInput);

        if (transform.position.x < leftBoundary)
        {
            transform.position = new Vector3(leftBoundary, transform.position.y, transform.position.z);
        }

        if (transform.position.x > rightBoundary)
        {
            transform.position = new Vector3(rightBoundary, transform.position.y, transform.position.z);
        }

        // This is the part i need help on!!!
        if (Input.GetKeyDown(KeyCode.Space))
        {
            pizza = Instantiate(pizzaPrefab, transform.position, pizzaPrefab.transform.rotation) as GameObject;

            if (pizza.transform.position.z > 35)
            {
                Destroy(pizza);
            }
        }
    }
}

CodePudding user response:

Your check for destroying "pizza" is INSIDE the check for the spacebar, meaning that it'll only attempt to destroy "pizza" if (y > 30 AND spacebar pressed)

Move your "pizza" destruction check to be OUTSIDE the spacebar if statement.

(Preferably, the Pizza object should have it's own MonoBehaviour checking it's position, rather than relying on the object that shot it, but I digress.)

//beginning of Update()

if (Input.GetKeyDown(KeyCode.Space))
{
    pizza = Instantiate(pizzaPrefab, transform.position, pizzaPrefab.transform.rotation) as GameObject;
}

if (pizza.transform.position.z > 35)
{
    Destroy(pizza);
}

//end of Update()
  • Related