【问题标题】:I want to access information from another script but I get this error " Int does not contain a definition for TakeDamage" Unity我想从另一个脚本访问信息,但出现此错误\" Int does not contain a definition for TakeDamage\" Unity
【发布时间】:2022-12-05 01:10:57
【问题描述】:

这是整个错误“int”不包含“TakeDamage”的定义,并且找不到接受类型“int”的第一个参数的可访问扩展方法“TakeDamage”(您是否缺少 using 指令或程序集引用?)

这是我应该从那里获取信息的记录

我在收到错误消息的地方写了一段文字

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

public class PlayerStatus : MonoBehaviour
{
//health

    public int health;
    public int maxHealth = 10;
    
    //Damage
    
    int dmg = 4;
    //XP
    
    public int xp;
    public int LevelUp = 10;
    
    // Start is called before the first frame update
    void Start()
    {
        health = maxHealth;
    }
    
    // Update is called once per frame
    public void TakeDamage(int amount)
    {
        health -= amount;
        if(health <=0)
        {
            Destroy(gameObject);
        }
    }

}

这是应该接收信息的脚本


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

public class EnmStatus : MonoBehaviour
{
public PlayerStatus playerHealth;
public int damage = 2;

    //health
    public int health;
    public int maxHeath = 10;
    
    // Start is called before the first frame update
    
    void Start()
    {
        health = maxHeath;   
    }
    
    // Update is called once per frame
    void Update()
    {
        
    }

*//Down here I receive the error*

    private void OnMouseDown()
    {
    
            health.TakeDamage(damage);

//     if(health \>= 1)
//     {
//         playerHealth.TakeDamage(damage);
//     }
}

    void TakeDamage(int amount)
    {
        health -= amount;
        if (health <= 0)
        {
            Destroy(gameObject);
        }
    }

}

当我点击他时应该会降低 ENM 的健康,之后如果 ENM 还活着我想降低玩家的健康(健康> = 1)

【问题讨论】:

    标签: c# visual-studio unity3d


    【解决方案1】:

    您正试图在整数类型上调用 .TakeDamage(damage),而不是通过 playerHealth 变量引用的 PlayerStatus 类。我假设这是您在这种情况下尝试调用的函数。

    我假设您已经使用 playerHealth 变量分配了对 PlayerStatus 的引用,但以防万一我添加了空检查。欢迎您省略它并将以下代码缩短为:

    playerHealth.TakeDamage(damage);
    

    或者,完整的代码将包括以下内容:

    private void OnMouseDown()
    {
        /*
         * This could also be written in one line using a null conditional operator
         * playerHealth?.TakeDamage(damage);
         */
        if(playerHealth != null)
        {
            playerHealth.TakeDamage(damage);
        }
    }
    

    如果您要调用在您的EnmStatus 中定义的TakeDamage 函数,则无需编写health.TakeDamage(damage)TakeDamage(damage) 就足够了,因为它是本地范围的。但我不确定为什么你会有这两个重复的功能。

    我建议复习 C# 编程的基础知识,也许可以通过 Unity Learn 免费提供的Beginner Scripting Tutorials

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 2022-12-27
      • 1970-01-01
      相关资源
      最近更新 更多