我想將 gunS 設定為 Shotgun 型別或 AR15 型別但不知道如何并且此代碼不起作用
public Shotgun gunS2;
public AR15 gunS3;
public MonoBehaviour gunS;
private void Start()
{
set();
}
public void set()
{
if(gunT.name == "Shotgun")
{
gunS = gunT.GetComponent<Shotgun>();
}
else
{
gunS = gunT.GetComponent<AR15>();
}
}
uj5u.com熱心網友回復:
給他們一個通用的介面。
interface IWeapon
{
}
class AR15 : IWeapon
{
}
class Shotgun : IWeapon
{
}
如果您的類以這種方式定義(您顯然必須添加實作),那么您可以撰寫一個可以包含任何IWeapon.
public IWeapon gunS;
public void set()
{
if(gunT.name == "Shotgun")
{
gunS = gunT.GetComponent<Shotgun>();
}
else
{
gunS = gunT.GetComponent<AR15>();
}
}
uj5u.com熱心網友回復:
使用基類和/或介面
public interface IWeapon
{
// whatever public properties and methods shall be accessible through this interface
}
public abstract class Weapon : MonoBehaviour //, IWeapon
{
// whatever fields, properties and methods are shared between all subtypes
// if using the interface implementation of it
}
進而
public class ShotGun : Weapon
// or if for some reason you don't want a common base class
//public class ShotGun : MonoBehaviour, IWeapon
{
// whatever additional or override fields, properties and methods this needs
// or if using the interface the implementation of it
}
和
public class AK74 : Weapon
// or if for some reason you don't want a common base class
//public class AK74 : MonoBehaviour, IWeapon
{
// whatever additional or override fields, properties and methods this needs
// or if using the interface the implementation of it
}
然后只需將相應的物件/組件拖到 Unity 中 Inspector 中的暴露槽中。
不需要你的gunT領域(無論它來自哪里)
// Already reference this via the Inspector in Unity
// then you don't need your Start/set method AT ALL!
public Weapon gunS;
如果由于某種原因這不是一個選項,例如如果只使用界面
public IWeapon gunS;
仍然不需要檢查名稱或進一步指定型別。GetComponent將回傳給定型別的第一個遇到的組件或從它繼承的型別。你可以簡單地做
void Awake()
{
// as fallback if for whatever reason you can't directly reference it via the Inspector
// (which doesn't seem to be the case since somewhere you get gunT from ...)
if(!gunS) gunS = /*Wherever this comes from*/ gunT.GetComponent<Weapon>();
// or i only using the interface
//if(!gunS) gunS = /*Wherever this comes from*/ gunT.GetComponent<IWeapon>();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339684.html
