![](/img/trans.png)
[英]A variable to hold value in this class to from another class in unity3d?
[英]UNity3D, return value from one class/method to another class/method in Unity3D
在Unity3D中,
我有一個武器腳本和一個耐力腳本。 我現在想做的是在武器擺動時消耗耐力。
我嘗試了我的代碼,並且已經使用了幾個小時。
我正在使用unity,因此它也給了我關於使用new的注釋,並且我應該使用Add.component等,因此我也很樂意回答該問題!
希望這篇文章在標題和信息/布局方面會更好一些,因為我非常疲倦且精力充沛。 我要休息片刻,然后再回來!
這是耐力系統 :
`
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);
}
}
您可以創建getter / setter方法來設置/獲取類A的屬性。在類B中,您可以創建類A的實例並訪問該服裝。
示例類A:
public class Genre
{
public string Name { get; set; }
}
B類的實例實例:
Genre genre = new Genre();
string name = genre.getName();
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.