Home > front end >  how can I make the game object disappear?
how can I make the game object disappear?

Time:09-17

when I was watching on YouTube, tutorials about endless runner on part 2, the game object wouldn't disappear when it hits the player

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

public class Obstacle : MonoBehaviour
{
    public int damage = 1;
    public float speed;

    private void Update()
    {
        transform.Translate(Vector2.left * speed * Time.deltaTime);
    }

    void onTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("rocket"))
        {
            //rocket takes damage 1
            other.GetComponent<rocket>().health -= damage;
            Debug.Log(other.GetComponent<rocket>().health);
            Destroy(gameObject);
        }
    }
} 
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class rocket : MonoBehaviour
{
    private Vector2 targetPos;
    public float Yincrement;

    public float speed;
    public float maxHeight;
    public float minHeight;

    public int health = 3;

    void Update()
    {
        if (health <= 0)
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }

        transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.UpArrow) && transform.position.y < maxHeight)
        {
            targetPos = new Vector2(transform.position.x, transform.position.y   Yincrement);
        }
        else if (Input.GetKeyDown(KeyCode.DownArrow) && transform.position.y > minHeight)
        {
            targetPos = new Vector2(transform.position.x, transform.position.y - Yincrement);
        }
    }
}

from this one https://www.youtube.com/watch?v=FVCW5189evI and I'm confused why it didn't work, can someone tell me what is wrong?

CodePudding user response:

if you want to destroy use this, Correct Method to get the game object when collide is: other.gameObject

void onTriggerEnter2D(Collider2D other)
 {
 if (other.CompareTag("rocket"))
  {
    //rocket takes damage 1
    other.gameObject.GetComponent<rocket>().health -= damage;
    Debug.Log(other.gameObject.GetComponent<rocket>().health);
    Destory(other.gameObject);
  }
}

CodePudding user response:

Use SetActive instead of Destroy Function.

void onTriggerEnter2D(Collider2D other)
{
    if (other.CompareTag("rocket"))
    {
        //rocket takes damage 1
       
          other.gameObject.GetComponent<rocket>().health -= damage;
     
        Debug.Log(other.gameObject.GetComponent<rocket>().health);

      gameObject.SetActive(false);// it'll Hide GameObject instead of Destroying
       // gameObject.SetActive(true);// to show again
    }
}
  • Related