如何检查gameObject是否具有特定属性?

时间:2018-03-04 00:44:00

标签: c# unity3d

我有一个具有public boolean isIndestructible = true属性的Player对象。我还有一个具有以下功能的Mine对象:

void OnCollisionEnter2D(Collision2D other) {
    if (other.gameObject.CompareTag("Player") && !other.gameObject.isIndestructible) {
        SceneManager.LoadScene("Game");
    }
}

基本上,如果Player对象不是坚不可摧的话,我只想重新加载游戏。但是这段代码不起作用(gameObject没有isIndestructible作为属性),那么找到这个代码的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

  

我有一个带有公共布尔值isIndestructible = true属性的Player对象。

所以你已经将MonoBehaviour附加到了Player对象,对吗?

<强> Player.cs

using UnityEngine;

public class Player : MonoBehaviour
{
    public bool isIndestructible {get; set;}
}

要获取isIndestructible中的媒体资源Mine

void OnCollisionEnter2D(Collision2D other) {
    var player = other.gameObject.GetComponent<Player>();
    if(player != null && player.isIndestructible){        
        SceneManager.LoadScene("Game");
    }
}
相关问题