在C#中访问非静态字段需要对象引用

时间:2017-03-12 17:14:46

标签: c# object unity3d reference

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 > 0)

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

1 个答案:

答案 0 :(得分:0)

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

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