【问题标题】:Unity C# How to check if library is existing in the projectUnity C#如何检查项目中是否存在库
【发布时间】:2017-11-29 16:40:33
【问题描述】:

有没有办法用脚本检查项目中是否存在统一库。 例如:

using UnityEngine.Advertisements;

如果存在,则执行以下操作:

Advertisements.IsReady();

感谢您的帮助!

【问题讨论】:

  • 如果您的项目中没有引用该库,编译器应该抱怨Advertisements.IsReady(); 并通知您using UnityEngine.Advertisements; 是未使用的引用或不知道您尝试引用的内容。
  • 是的,但我想让脚本仅在库存在时才执行操作,如果不存在则不采取任何操作。
  • 请看我的回答,对你有帮助吗?

标签: c# unity3d


【解决方案1】:

看一下MSDN documentation关于方法Assembly.GetReferencedAssemblies()。此方法返回一个AssemblyName[],其中包含此程序集引用的所有程序集的名称。换句话说,引用的程序集是例如图书馆。然后,您可以轻松地将代码包装在 if 语句中,以便在数组中包含所需的库(名称)时执行代码,或者不执行。

示例代码:

Assembly currentAssembly = typeof(/*enter the class name which contains the assembly references*/).Assembly;

AssemblyName[] referencedAssemblies =  currentAssembly.GetReferencedAssemblies();

foreach (var refAssembly in referencedAssemblies)
{
    if (assembly == /*the name of the assembly you want to check that has to exist*/)
    {
        //...do your work if the assembly exists

        break;
    }
}

这背后的技术称为Reflection,我强烈推荐你阅读它,它非常有趣。

【讨论】:

    【解决方案2】:

    在这种情况下你不能使用 if else 语句,因为编译器会报错,例如if(false) Advertisements.IsReady(); 编译器找不到类型广告。

    但是还有另一种方法,您可以使用反射从程序集中获取类型。然后获取要调用的方法,但这仍然不是实际的方法。

    你可能想用常量代替,或者使用 ClassAttribute 来告诉这个脚本启用广告,但是using UnityEngine.Advertisements;是必须的,你可以为此创建自定义的monobehaviour,然后将它继承到你的应用程序中,这样你就可以隐藏此行using UnityEngine.Advertisements;

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-25
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多