unity3d 我想从另一个脚本访问信息,但收到错误消息“Int does not contain a definition for TakeDamage”Unity

f5emj3cl  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(146)

这是完整的错误'int'不包含'TakeDamage'的定义,而且找不到可存取的扩充方法'TakeDamage'接受型别'int'的第一个参数(您是否遗漏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)

k4emjkb1

k4emjkb11#

您正在尝试对整数类型调用.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#编程的基础知识,也许可以通过UnityLearn上免费提供的Beginner Scripting Tutorials来学习

相关问题