如何使用Unity2020 C#将UnityEngine.Object转换为布尔



我正在开发一款可以杀死和被敌人杀死的游戏如果你杀死一个敌人,他的精灵就会改变当我杀死敌人时,我希望敌人的boxcollider2D上的IsTrigger选项为假,这样他的对撞机就可以留下来,但我仍然可以在他身上行走它在无法将bool转换为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);
}
}
}

在您的代码中,您试图销毁不是游戏对象的collision.GetComponentInChildren<BoxCollider2D>().isTrigger = true

如果你想销毁游戏对象,只需通过'collsiion.GetComponentInChildren(('

此外,我不明白你为什么要破坏BoxCollider2D。如果你只想禁用它,我认为禁用它就足够了,而不是摧毁它

最新更新