我需要將公共類中的受保護變數呼叫到另一個公共類的私有方法中的 if 陳述句中 我正在統一撰寫視頻游戲,我需要使用 bool 變數(顯示角色是否體力不足)在 if 陳述句中確定角色是否可以運行這是我的代碼的樣子,排除了與問題無關的所有內容
Public class CharacterStats : MonoBehaviour
{
[SerialzeField] protected bool Tired;
}
Public class PlayerMovement : MonoBehaviour
{
Private void HandleRunning()
{
If (Input.GetKeyDown(KeyCode.LeftShift) && X != True)
{
Speed = RunSpeed;
}
}
}
X is where I want the Tired variable to be.
uj5u.com熱心網友回復:
看看這個,這是人們通常會這樣做的方式:
using System;
namespace XYZ
{
public class CharacterStats : MonoBehaviour
{
[field: SerializeField] public bool Tired { get; protected set; }
}
public class PlayerMovement : MonoBehaviour
// this should be in its own file else Unity will cry
{
public CharacterStats Stats; // set this value in inspector
public void Whatever()
{
if (Stats == null)
return;
if (Stats.Tired)
{
Console.WriteLine("Whatever...");
}
}
}
}
嘗試直接訪問該值將不起作用,因為它不是static.
如果你想制作它static,CharacterStats應該制作成一個單身人士。
沒有一種尺寸適合 Unity 的所有單例,每個變體都有特定的用途:
https://www.google.com/search?q=monobehaviour singleton
但是,請繼續閱讀,角色統計資訊永遠不應該是單身人士。這是因為,據說游戲中有很多角色,即 實體,因此擁有一個static實體(這意味著只有一個)根本沒有意義。
另外,不要嘗試添加staticbefore bool IsTired,你只會用腳射擊自己:
- 所有角色都會有相同的疲倦狀態
- 該值不會被 Unity 保留,因為它不會序列化靜態成員。
TL; 博士;
做我發布的代碼,這是 Unity 的方式。
uj5u.com熱心網友回復:
使用public只讀屬性,例如
public class CharacterStats : MonoBehaviour
{
// Keep you serialized field protected
[SerialzeField] protected bool Tired;
// Have a public read-only accessor property
public bool IsTired => Tired;
}
然后例如
public class PlayerMovement : MonoBehaviour
{
// Somehow you will need to get a reference to the CharacterStats instance
// e.g. via the Inspector
[SerializeField] private CharacterStats stats;
[SerializeField] private float RunSpeed;
private float Speed;
private void HandleRunning()
{
if (Input.GetKeyDown(KeyCode.LeftShift) && !stats.IsTired)
{
Speed = RunSpeed;
}
}
}
總的來說:修理你的外殼!在c#所有關鍵詞中都是低調的!
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/362700.html
上一篇:Pythonmatplotlib代碼掛在plt.plot()上
下一篇:子彈不破壞
