【问题标题】:An object reference is required to access non-static field in C#访问 C# 中的非静态字段需要对象引用
【发布时间】:2017-03-12 17:14:45
【问题描述】:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyAttack : MonoBehaviour {
    public float timeBetweenAttacks = 0.5f;
    public int attackDamage = 10;
    Animator anim;
    GameObject Player;
    PlayerHealth playerHealth;

    //EnemyHeath enemyhealth;

    bool playerInRange;
    float timer;
    private Animator animator = null;

    void Awake() {
        Player = GameObject.FindGameObjectWithTag ("Player");
        playerHealth = Player.GetComponent<PlayerHealth> ();

        //enemyHealth = GetComponent<EnemyHealth> ();

        anim = GetComponent <Animator> ();
    }


    void Attack(Collider other) {
        if (other.gameObject == Player) {
            playerInRange = true;
            animator.SetBool ("idle0ToAttack1", true);
        }
    }

    void Attack1(Collider other) {
        if (other.gameObject == Player) {
            playerInRange = false;
        }
    }

    void Update() {
        timer +=Time.deltaTime;

        if (timer >= timeBetweenAttacks /*&& enemyHealth.currentHealth > 0*/) {
            AttackPlayer ();
        }

        if (playerHealth.currentHealth <= 0) {
            Destroy (this.Player);
        }
    }

    void AttackPlayer() {
        timer = 0f;
        if (PlayerHealth.currentHealth > 0) {
            playerHealth.TakeDamage (attackDamage);
        }
    }
}

错误在于最后一个方法void AttackPlayer() if(PlayerHealth.currentHealth &gt; 0)

我正在 Unity 中制作第一人称射击游戏,如果可能,请告诉我一些关于我上面编写的玩家死亡动画师代码的更多建议。

【问题讨论】:

  • PlayerHealth 是一个类。您不能在类上调用实例方法。您需要在类(对象)的实例中调用它。否则,您希望PlayerHealth.currentHealth 指的是什么?哪个球员的健康状况?

标签: c# object unity3d reference


【解决方案1】:
void AttackPlayer()
{
    timer = 0f;
    if(playerHealth.currentHealth > 0)
    {
        playerHealth.TakeDamage(attackDamage);
    }
}

我已经更正了代码。使用PlayerHealth 而不是您的意思playerHealth 是一个简单的错误。使用大写是指类本身。小写字母将引用您在此类前面定义的当前对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多