mes*_*guy 5 c# generics types unity-game-engine unityscript
我正在编写一个方法来检查gameObject是否有一个组件.
这里是:
public static bool HasComponent <T>(this GameObject obj)
{
return obj.GetComponent<T>() != null;
}
Run Code Online (Sandbox Code Playgroud)
而我正在使用它:
void Update()
{
if (Input.GetKey("w"))
{
if (gameObject.HasComponent<Rigidbody>())
{
print("Has a rigid body.");
return;
}
print("Does not have rigid body.");
}
}
Run Code Online (Sandbox Code Playgroud)
gameObject没有刚体,但它仍然打印它确实有.
Fat*_*tie 10
它只是......
public static bool HasComponent <T>(this GameObject obj) where T:Component
{
return obj.GetComponent<T>() != null;
}
Run Code Online (Sandbox Code Playgroud)
请注意,你忘记了
第一行的一部分!
有了这个语法错误,扩展名是没有意义的:它总是找到"某个组件"(因为T有点"空白"),因此永远不会为空.这只是一个语法错误.
注意.
解释"什么是扩展".
对于那些不熟悉c#类别的人来说这就是c#中的"扩展"...这里是一个简单的教程 ......
扩展在Unity中绝对至关重要 - 您在每行代码中至少使用一次.基本上在Unity中,您几乎可以在扩展中执行所有操作. 请注意,OP甚至没有显示包装类.你可以在这样的文件中找到它:
public static class ExtensionsHandy
// The wrapper class name is actually irrelevant - it is not used at all.
// Choose any convenient name for the wrapper class.
{
public static bool HasComponent <T>(this GameObject obj) where T:Component
{
return obj.GetComponent<T>() != null;
}
public static bool IsNear(this float ff, float target)
{
float difference = ff-target;
difference = Mathf.Abs(difference);
if ( difference < 20f ) return true;
else return false;
}
public static float Jiggle(this float ff)
{
return ff * UnityEngine.Random.Range(0.9f,1.1f);
}
public static Color Colored( this float alpha, int r, int g, int b )
{
return new Color(
(float)r / 255f,
(float)g / 255f,
(float)b / 255f,
alpha );
}
}
Run Code Online (Sandbox Code Playgroud)
在示例中,我包含了三个更典型的扩展.通常你会有几十甚至几百个.(您可能更喜欢将它们分组在不同的HandyExtensions文件中 - 包装类的文件名完全不相关.)每个工程师和团队都有自己一直使用的"公共扩展".
注意,这里例如实例我是问有关在类别已经超出我的东西一个棘手的问题.(谢天谢地,EricL就在那里!)顺便说一句,在大多数/某些/较旧的语言中,你称之为"类别".在c#中它是一个"扩展",但是人们总是说"类别"或"扩展".
正如我所说,你在Unity中不断使用它们.干杯
如果你喜欢那种东西,这里有一个漂亮的东西:
// Here's an unbelievably useful array handling category for games!
public static T AnyOne<T>(this T[] ra) where T:class
{
int k = ra.Length;
int r = UnityEngine.Random.Range(0,k);
return ra[r];
}
Run Code Online (Sandbox Code Playgroud)