我如何在Unity中使用行为

本文关键字:Unity | 更新日期: 2023-09-27 17:58:21

我对c#和一般编码都很陌生。

我得到的是一个公开int为50(伤害)的武器脚本。然后我得到了另一个剧本,那就是敌人的健康。

现在我想做的是使用武器脚本中的值将其应用于敌人的健康脚本,而我不知道如何做到这一点。

我知道这很简单,但我一直在用头撞墙,试图弄清楚这件事。

请帮忙!

武器.cs

using UnityEngine;
using System.Collections;
public class Weapon : MonoBehaviour {
    static Animator anim;
    public GameObject hitbox;
    public int damage = 50;
    private AudioSource MyAudioSource;
    private AudioClip WeaponSound;
    void Start () {
        anim = GetComponentInParent<Animator>();
        MyAudioSource = GetComponent<AudioSource>();
        GetComponent<EnemyHealth>().TakeDamage(damage);                 
    }
    void Update () {
        attack();
        block();
    }
    public void attack() {
        if (Input.GetButtonDown("Fire1")) {
            GetComponent<EnemyHealth>().TakeDamage(damage);
            anim.SetBool("IsAttacking", true);
            hitbox.SetActive(true);
            Debug.Log("hit");
            MyAudioSource.PlayOneShot(WeaponSound);
        }
        else {
            anim.SetBool("IsAttacking", false);
            hitbox.SetActive(false);
        }
    }
    public void block() {
        if (Input.GetButtonDown("Fire2")) {
            anim.SetBool("IsBlocking", true);
        }
        else {
            anim.SetBool("IsBlocking", false);
        }
    }
}

EnemyHealth.cs

using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour {
    public int maxHealth = 100;
    private int currentHealth;        
    private Animator animator;
    void Start () {
        currentHealth = maxHealth;
        animator = GetComponent<Animator>();
    }
    public void OnTriggerEnter(Collider other) {
        other.GetComponent<Weapon>().attack();
    }
    public void TakeDamage(int _damage) {
        currentHealth -= _damage;
        animator.SetTrigger("IsHit");
        if(currentHealth <= 0) {
            Die();
        }
    }
    void Die() {
        animator.SetBool("Isdead", true);
        Destroy(gameObject);
    }
}

我如何在Unity中使用行为

假设它们都在c#中的另一个主类中实例化(意味着它们与另一个不一样),那么只需使用"."操作员访问类中的公共元素、属性和函数

main()
{
    EnemyHealth myehlth = new EnemyHealth();
    Weapon myweapn = new Weapon ();
    myehlth.TakeDamage(myweapn.damage); 
}

在这里我使用了"。"操作员访问您武器类别中的公共损坏,然后使用"。"oeprator将其传递给健康类中的公共TakeDamage函数

答案很简单!感谢noone392

main()
{
    
    Weapon myweapn = new Weapon ();
    TakeDamage(myweapn.damage); 
}