簡體   English   中英

Visual Studio 無法從另一種方法中找到 TakeDamage 的定義

[英]Visual studio can't find definition for TakeDamage from another method

我正在 Unity 中制作健康和傷害腳本。 我有錯誤 CS0117 'PlayerHealth' 不包含 'TakeDamage' 的定義

我希望玩家有 20 個生命值,當觸摸 object 時,它會傷害他。 我嘗試在谷歌上搜索,但沒有找到答案。

玩家健康腳本:


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

public class NewBehaviourScript : MonoBehaviour
{
    public int health = 20;

    public void TakeDamage(int damage)
    {
        health -= damage;

        if (health <= 0)
        {
            Destroy(gameObject, 0.3f);
        }
    }
}

對於 EnemyDamage 腳本,我使用以下代碼:

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

public class PlayerHealth : MonoBehaviour
{
    public int DMG;
    float cooldown = 0f;

    private void Update()
    {
        Debug.Log(cooldown);
        cooldown -= Time.deltaTime;
    }

    private void OnCollisionEnter(Collision collision)
    {
        PlayerHealth health = collision.gameObject.GetComponent<PlayerHealth>();
        if (cooldown <= 0)
        {
            if (health != null)
            {
                PlayerHealth.TakeDamage(DMG);//here is the error
            }
            cooldown = 1f;
        }
    }
}

PlayerHealth.TakeDamage(DMG); 嘗試在 class TakeDamage PlayerHealth沒有這樣的方法,因此出現錯誤。 無論如何,您的代碼有點亂,讓我們清理一下。 將此腳本附加到可能失去健康的游戲對象(例如玩家):

public class Health : MonoBehaviour // you called it NewBehaviourScript
{
    public int health = 20;

    public void TakeDamage(int damage) {
        health -= damage;
        if (health <= 0) {
            Destroy(gameObject, 0.3f);
        }
    }
}

將此腳本附加到可能造成損壞的游戲對象:

public class Damage : MonoBehaviour  // you called it PlayerHealth (?!)
{
    public int DMG;
    float cooldown = 0f;

    void Update()
    {
        Debug.Log(cooldown);
        cooldown -= Time.deltaTime;
    }

    void OnCollisionEnter(Collision collision)
    {
        if (cooldown <= 0f) {
            Health health = collision.gameObject.GetComponent<Health>();
            if (health != null) {
                // call TakeDamage on the collided >instance<
                health.TakeDamage(DMG); 
            }
            cooldown = 1f;
        }
    }
}

這應該為您提供一個適當的碰撞器設置的起點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM