在团结3d的脚本

时间:2017-12-11 09:43:33

标签: c# unity3d monodevelop

我在Unity3D遇到问题。我有相同的健康脚本附加到玩家和敌人。我希望在玩家死亡时显示游戏结束消息,但问题是玩家和敌人在死亡时都会显示游戏结束消息。

我的代码看起来像是:

public class CharacterStats : MonoBehaviour 
{
    // Use this for initialization
    void Start () 
    {
    }

    // Update is called once per frame
    void Update () 
    {
        health = Mathf.Clamp (health, 0, 100);
    }

    public void damage(float damage)
    {
        health -= damage;
        if(health<=0)
        {
            Die();
            Application.LoadLevel(gameover);
        }
    }

    void Die()
    {
        characterController.enabled = false;
        if (scriptstodisable.Length == 0)
            return;
                 foreach (MonoBehaviour scripts in scriptstodisable)

                scripts.enabled = false;
                 if (ragdollmanger != null)
                     ragdollmanger.Raggdoll();
    }
}

2 个答案:

答案 0 :(得分:2)

当你为玩家和敌人使用1个脚本时。您应该为两者创建不同的类并实现接口或从基类派生以实现运行状况:

public class Character : MonoBehaviour 
{
    public float Health;

    public virtual void Damage(float damageValue) 
    {
        Health -= damageValue;
    }

    public virtual void Die()
    {

    }
}

public Enemy : Character
{
    public override void Die()
    {
        // do enemy related stuff
    }
}

public Player : Character
{   
    public override void Die()
    {
        // do player related stuff.
        // like game over screen
    }
}

希望这会有所帮助:)

答案 1 :(得分:1)

您可以使用bool检查CharacterStats是否附加到播放器,例如通过向玩家游戏对象添加名为”Player”的标签并检查gameObject.tag == “Player”,或者您可以等同地命名游戏对象”Player”,如果你愿意,可以检查gameObject.name

然后,只有当游戏对象是玩家(isPlayer为真)时,您才可以通过消息运行游戏功能。

public class CharacterStats : MonoBehaviour 
{
    bool isPlayer = false;

    // Use this for initialization
    void Start () 
    {
        if(gameObject.tag == “Player”) 
        {
            isPlayer = true;
        }      
    }

    // Update is called once per frame
    void Update () 
    {
        health = Mathf.Clamp (health, 0, 100);
    }

    public void damage(float damage)
    {
        health -= damage;
        if(health<=0)
        {
            if(isPlayer)
            {
                // Do Player-only stuff
            }

            // Do Stuff for both players and enemies
        }
    }
}