UNity3D,从一个类/方法返回值到Unity3D中的另一个类/方法

时间:2016-07-25 18:52:06

标签: c# unity3d

在Unity3D中,

我有一个武器脚本和一个耐力脚本。我现在要做的是在武器摆动时消耗耐力。

我尝试了我的代码,并且我已经玩了几个小时了。

我正在使用统一,所以它也给了我关于使用new的评论,我应该使用Add.component等,所以我也很感激这个问题的答案!

希望这篇文章在标题和信息/布局方面有所改善,因为我非常疲惫,精力充沛。在我回到它之前,我要休息一下!

这是Stamina系统

`

public class HandS : MonoBehaviour {

public int startingHealth = 100;
public int currentHealth;
public int healthReg;
Sword mySword;

bool isRegenHealth;

public float startingStam = 100;
public float currentStam;
public float stamReg;

bool isRegenStam;

void Awake()
{
    currentStam = startingStam;   
}

void Update()
{
    if (currentStam != startingStam && !isRegenStam)
    {
        StartCoroutine(RegainStamOverTime());
    }
}

private IEnumerator RegainStamOverTime()
{
    isRegenStam = true;
    while (currentStam < startingStam)
    {
        Stamregen();
        ReduceStamina(mySword.stamDrain);
        yield return new WaitForSeconds(1);
    }
    isRegenStam = false;
}

public void Stamregen()
{
    currentStam += stamReg;
}

public void ReduceStamina(float _stamDrain)
{
    currentStam -= _stamDrain;
}

}

`

这是Sword脚本

using UnityEngine;
using System.Collections;

public class Sword : MonoBehaviour {
static Animator anim;
public GameObject hitbox;
HandS hp = new HandS();
public int Sworddamage = 20;
public float sec = 0.5f;
public float maxStamina = 20;

public float  AttackCD;
public float delayBetweenAttacks = 1.5f;
public float stamDrain = 50;

public AudioSource WeaponSource;
public AudioClip WeaponSound;

void Start () {
    anim = GetComponentInParent<Animator>();
    WeaponSource = GetComponent<AudioSource>();
}

// Update is called once per frame
void Update () {
    attack();
    block();

}

public void attack()
{
        if (Input.GetButtonDown("Fire1") && Time.time > AttackCD)
    {
        AttackCD = Time.time + delayBetweenAttacks;
        anim.SetBool("IsAttacking", true);
        hitbox.SetActive(true);
        StartCoroutine(LateCall());
        WeaponSource.PlayOneShot(WeaponSound);
        Debug.Log("hit");
        hp.ReduceStamina(stamDrain);
    }
    else
    {
        anim.SetBool("IsAttacking", false);
    }  

}

public void block()
{
    if (Input.GetButtonDown("Fire2"))
    {
        anim.SetBool("IsBlocking", true);
    }
    else
    {
        anim.SetBool("IsBlocking", false);
    }
}

IEnumerator LateCall()
{
    yield return new WaitForSeconds(sec);
    hitbox.SetActive(false);
}

}

1 个答案:

答案 0 :(得分:0)

您可以创建getter / setter方法来设置/获取A类属性。 在B类中,您可以创建A类实例并访问该属性。

示例A类:

public class Genre
{
    public string Name { get; set; }
}

B类中的示例实例:

Genre genre = new Genre();
string name = genre.getName();

希望它有所帮助。