我正在為我的 FPS 游戲開發一個簡單的武器控制器,并在嘗試使其動態化時遇到了一個問題。當玩家拿起武器時,我想要發生的事情是將武器統計資料和效果設定為默認值。為此,每個武器都有一個腳本
weapon.name "Stats"
但是我在參考所述腳本時遇到問題。現在,這就是我的代碼的樣子:
string weaponScriptName = weapon.name "Stats";
weapon.GetComponent<weaponScriptName>().UseWeapon();
其中weapon代表當前裝備的武器的gameobject. 顯然,這不起作用,我在 Unity 幫助頁面上找到的各種實作只會導致更多錯誤。我能做些什么來解決這個問題?
謝謝你。
uj5u.com熱心網友回復:
如果我理解正確,你想做類似的事情GetComponent<"Transform">()嗎?如果是這樣,你應該做的GetComponent("Transform");,而不是
uj5u.com熱心網友回復:
GetComponent 有多個多載。
有您所指的通用版本 - 最常用的一個
T GetComponent<T>()只能與編譯時常量型別引數一起使用,例如
var renderer = GetComponent<Renderer>();有一個使用動態
TypeComponent GetComponent (Type type)喜歡
// Just an example, there are many ways of getting a type var type = typeof(Renderer); var renderer = (Renderer) GetComponent(type);最后有一個
stringComponent GetComponent (string typeName);喜歡
// Again just an example, there are many ways of getting type names // Especially when dealing with multiple assemblies you might even have to use the AssemblyQualifiedName var renderer = (Renderer) GetComponent("Renderer");
請注意,對于任何動態版本,您都必須鍵入強制轉換,或者如果只有通用Component參考就足夠了,您當然可以使用它。
但是,如前所述,無論如何都不要使用string版本!
它總是緩慢且容易出錯。而是使用例如一些公共基類或介面,或使用列舉或Dictionary決定為哪個狀態做什么。
所以我寧愿有例如
public interface IWeapon
{
void UseWeapon();
}
然后你的每一種不同的武器都可以實作這個介面
public class WeaponA : MonoBehaviour, IWeapon
{
public void UseWeapon ()
{
Debug.Log("Used Weapon A");
}
}
public class WeaponB : MonoBehaviour, IWeapon
{
public void UseWeapon ()
{
Debug.Log("Used Weapon B");
}
}
你的代碼只是
var weapon = someObject.GetComponent<IWeapon>(). UseWeapon();
或者,如果您的武器都共享一些通用實作,例如拾取等,而具有通用基類
public abstract class BaseWeapon : MonoBehaviour
{
// Everything that all weapons share as behavior and properties
// every subclass HAS TO implement and override this method
public abstract void UseWeapon ();
// Alternatively if there even is some common behavior
// subclasses CAN but don't have to override this
//public virtual void UseWeapon ()
//{
// // Implementation that is the default behavior
//}
}
進而
public class WeaponA : BaseWeapon
{
public override void UseWeapon ()
{
Debug.Log("Used Weapon A");
// If using virtual before then this class IGNORES and fully overwrites the default implementation
}
}
public class WeaponB : BaseWeapon
{
public override void UseWeapon ()
{
// If using virtual and you WANT the default behavior then add
//base.UseWeapon();
Debug.Log("Used Weapon B");
}
}
你的代碼只是
var weapon = someObject.GetComponent<BaseWeapon>(). UseWeapon();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/335671.html
