UNity3D,返回UNity3D中一个类/方法到另一个类或方法的值
本文关键字:UNity3D 方法 另一个 一个 返回 | 更新日期: 2023-09-27 17:58:36
在Unity3D中,
我有一个武器脚本和一个耐力脚本。我现在想做的是在武器摆动时消耗体力。
我试过我的代码,已经玩了几个小时了。
我正在使用unity,所以它也给了我一个关于使用new的评论,我应该使用addcomponent等,所以我也很感激这个问题的答案!
希望这篇文章在标题和信息/布局方面会好一点,因为我很累,精力不足。在我回去之前,我要休息一下!
这是耐力系统:
`
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;
}
}
`
这是剑的脚本:
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();
希望能有所帮助。