Search Unity

Question How do you remove an object in the game via script?

Discussion in 'Scripting' started by unrealsog, Jul 1, 2022.

  1. unrealsog

    unrealsog

    Joined:
    Jul 1, 2022
    Posts:
    1
    Hello! So I'm trying to create a script where once the player hits an obstacle, the player will be shot up and movement will be disabled, and the ground (which is just one object) will be destroyed.

    However, I cannot figure out how to remove an object from Unity, I've tried to find it on the forums but perhaps it's outdated since it doesn't work in my case.

    Please give me as much constructive criticism as you like, I'm very new to Unity and C# and game development as a whole and I'd love to learn.



    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PlayerCollision : MonoBehaviour
    4. {
    5.     public PlayerMovement movement;
    6.     public Rigidbody rb;
    7.    
    8.     //within the curly brackets, the script will be called whenever a collision occurs
    9.     void OnCollisionEnter(Collision collisionInfo)
    10.         {
    11.             if(collisionInfo.collider.tag == "Obstacle")
    12.                 {
    13.                   rb.AddForce(0,2000,0 * Time.deltaTime);
    14.                   movement.enabled = false;
    15.                   //attempting to remove ground post-collision
    16.                   Remove(Ground);
    17.                
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    Destroy() is the reference way to remove anything in Unity. There are other variations and arguments if you check the docs.