Search code examples
c#unity-game-engineimplicit-conversion

How can I convert UnityEngine.Object into a bool with Unity2020 C#


I am working on a game where you can kill and be killed by enemies If you kill an enemy his sprite will change I want the IsTrigger option on the enemy's boxcollider2D to be false when I kill him so that his collider stays but I could still walk on him It puts an error canot convert bool to UnityEngine.Object

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

public class PlayerMove : MonoBehaviour
{
    Rigidbody2D rb;
    SpriteRenderer sr;
 
    public float jumpHeight = 5f;
    public float moveSpeed = 4f;
    public float coins = 0f;
    public bool canJump = true;
    public Sprite DeadEnemy;
    public GameObject EnemySquare;


    // Start is called before the first frame update

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        sr = GetComponent<SpriteRenderer>();

    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            rb.velocity = new Vector2(rb.velocity.x, +jumpHeight);
            canJump = false;
        }
        if (Input.GetKey(KeyCode.D))
        {
            rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
        }
        if (Input.GetKey(KeyCode.A))
        {
            rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.CompareTag("Coin1"))
        {
            print("Coin1");
            Destroy(collision.gameObject);
            coins = coins + 1;
        }
        if(collision.CompareTag("Chest"))
        {
            print("Coin1");
            Destroy(collision.gameObject);
            coins = coins + 2;
        }
        if(collision.CompareTag("KillEnemy"))
        {
            Destroy(collision.GetComponentInChildren<BoxCollider2D>().isTrigger = false);//This is where the problem comes from
            print("Collision");
            coins = coins + 3;
            Destroy(EnemySquare);
            collision.gameObject.GetComponent<SpriteRenderer>().sprite = DeadEnemy;
        }
        if(collision.CompareTag("KillBlock"))
        {
            print("Collision");
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }
    }
}

Solution

  • In your code, you tried to destroy collision.GetComponentInChildren<BoxCollider2D>().isTrigger = true, which is not gameobject.

    If you want to destroy gameobject, just pass 'collsiion.GetComponentInChildren()'

    Also, I cannot understand why you try to destroy BoxCollider2D. If you want to just disable it, I think It will be sufficient to disable it, not destroy it.