【问题标题】:how to change a get component class base on string?如何根据字符串更改获取组件类?
【发布时间】:2021-01-26 12:49:51
【问题描述】:

所以我尝试使用已通过参数传递到 slot.GetComponent().level++ 的 compToGet 字符串;

upgradeFoundation() 将在按钮单击时调用。 并且实际上有很多具有类似功能的按钮(例如:upgradeTurret()、upgradeTurret2() 等) 这就是为什么我试图根据您单击的按钮更改 compToget 字符串的值并使用该新字符串以该新字符串的名称获取组件,但它似乎不能那样工作并且我不知道它会如何以任何其他方式工作,任何帮助将不胜感激。

    public void upgradeFoundation()
    {
        float upgFoundationCost = slotGroup.transform.Find(slotName).gameObject.GetComponent<Slot>().upgFoundationCost;
        Upgrade(upgFoundationCost, "Foundation");
    }

    public void Upgrade(float upgCost, string compToGet)
    {
        GameObject slot = slotGroup.transform.Find(slotName).gameObject;

        if (inGameUIManagerScript.money >= upgCost)
        {
            Type compToGetType = Type.GetType(compToGet); //im not sure how to convert a string into a type
            slot.GetComponent<compToGetType>().level++; //this is the error line saying im treating a var like a type
        }

    }

提前谢谢你。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    与您的previous question 完全相同的问题 => 您不能使用泛型! 而是使用GetComponent(compToGetType);

    但是我删除了重复项,因为您仍然需要将 cast 转换为您的实际类型,这绝不是微不足道的!

    => 再次我只能推荐:不要使用字符串!


    而是有一个通用的基类或接口,例如

    public abstract class BaseComponent : MonoBehaviour
    {
        private int level;
        // public read-only access
        public int Level => level;
    
        public virtual void Upgrade()
        {
            level++;
        }
    
        // Other properties and methods all your components have in common
        // Also get into "virtual" and "abstract" members!
    }
    

    并从中继承你的东西

    public class Foundation : BaseComponent
    {
        // Additional stuff specific to the foundation
        // overrides for the virtual and abstract members
    }
    
    public class Turret : BaseComponent
    {
        // Additional stuff specific to the turret
        // overrides for the virtual and abstract members
    }
    
    //Maybe this would even inherit from Turret instead?
    public class Turret2 : BaseComponent
    {
        // Additional stuff specific to the turret2
        // overrides for the virtual and abstract members
    }
    

    最后改用那个公共基础:

    public void UpgradeComponent()
    {
        slot.GetComponent<BaseComponent>().Upgrade();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 2023-03-18
      • 2011-05-13
      • 2015-10-09
      • 1970-01-01
      相关资源
      最近更新 更多