C# 为什么我的敌人根本不追我,当我告诉他停止追我时,他的生命为0?

C# 为什么我的敌人根本不追我,当我告诉他停止追我时,他的生命为0?,c#,unity3d,C#,Unity3d,我的代码中有一个问题我不理解,也找不到解决方案。问题是当我添加代码行ifdistToPlayer>agroRange | | currentHealth时,您在EnemyAgro中获得实际敌人当前生命值的唯一时间是在您的Start方法中。您以后不会在更新中获得更新的值 请记住,只有在初始化组件时才调用start…从那时起,引擎每帧只调用Update 在更新函数中设置curentHealth=enemyHealth.Health 或者,更好的是,只需将update语句中的代码更改为 voi

我的代码中有一个问题我不理解,也找不到解决方案。问题是当我添加代码行ifdistToPlayer>agroRange | | currentHealth时,您在EnemyAgro中获得实际敌人当前生命值的唯一时间是在您的Start方法中。您以后不会在更新中获得更新的值

请记住,只有在初始化组件时才调用start…从那时起,引擎每帧只调用Update

在更新函数中设置curentHealth=enemyHealth.Health

或者,更好的是,只需将update语句中的代码更改为

    void Update()
    {
        float distToPlayer = Vector2.Distance(transform.position, player.position);

        if(distToPlayer < agroRange && enemyHealth.health > 0){
            ChasePlayer();
         else
         {
             StopChasingPlayer();
         }   

    }

这是一个学习如何使用调试自己的代码的好机会,但问题不是代码不工作或有错误。问题是我没有按照我告诉他的去做,我也没有必要的知识来修复代码正按照你告诉它的去做。如果您不明白自己做错了什么,使用调试器会告诉您。顺便问一下,void Update{health=health;}的这一行/方法是什么^^是的,我这样做了,但正如我所说的……当我把它放在if The enemyHealth.health>0中时,它不是在追我……我尝试在两个ifs中都放上不同的条件,例如ifdistToPlayer=0{ChasePlayer;ifdistToPlayer
And the enemy agro...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyAgro : MonoBehaviour
{

    
    public GameObject Enemy;
    private EnemyHealth enemyHealth;
    private int curentHealth;
    [SerializeField]
    Transform player;
    [SerializeField]
    float agroRange;
    [SerializeField]
    float moveSpeed;

    public Rigidbody2D rb2d;

     public void Start()
    {
        enemyHealth = enemyHealth.GetComponent<EnemyHealth>();
        curentHealth = enemyHealth.health;
        rb2d = GetComponent<Rigidbody2D>();
    }

    
     void Update()
    {    
        
        
        float distToPlayer = Vector2.Distance(transform.position, player.position);

        if(distToPlayer < agroRange){
            ChasePlayer();
        }
        if(distToPlayer > agroRange || currentHealth <= 0){
            Debug.Log("Chase Stoped");
            StopChasingPlayer();
        }
        
    }

    private void ChasePlayer(){
        
        if(transform.position.x < player.position.x){
            rb2d.velocity = new Vector2(moveSpeed,0);
            transform.localScale = new Vector2(1,1);
            
        }
        else if(transform.position.x > player.position.x){
            rb2d.velocity = new Vector2(-moveSpeed,0);
            transform.localScale = new Vector2(-1,1);
        }
        }
    

    public void StopChasingPlayer(){
        rb2d.velocity = Vector2.zero;
        }


    }
    void Update()
    {
        float distToPlayer = Vector2.Distance(transform.position, player.position);

        if(distToPlayer < agroRange && enemyHealth.health > 0){
            ChasePlayer();
         else
         {
             StopChasingPlayer();
         }   

    }