c# - How to check if a game object has a component method in Unity? -
i writing method check if gameobject has component.
here is:
public static bool hascomponent <t>(this gameobject obj) { return obj.getcomponent<t>() != null; }
and i'm using this:
void update() { if (input.getkey("w")) { if (gameobject.hascomponent<rigidbody>()) { print("has rigid body."); return; } print("does not have rigid body."); } }
the gameobject not have rigid body still printing have.
it just...
public static bool hascomponent <t>(this gameobject obj) t:component { return obj.getcomponent<t>() != null; }
note forgot the
where t:component
part of first line!
with syntax error, extension meaningless: it's finding "some component" (since t sort of "blank") , hence never null. it's syntax error.
note.
explanation of "what heck extension".
for reading not familiar categories in c# .. "extensions" in c# ... here's easy tutorial ...
extensions absolutely critical in unity - use them @ least once in every line of code. basically in unity in extension. note op did not bother showing wrapper class. you'd have in file this:
public static class extensionshandy // class name irrelevant , not used { public static bool hascomponent <t>(this gameobject obj) 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( float alpha, int r, int g, int b ) { return new color( (float)r / 255f, (float)g / 255f, (float)b / 255f, alpha ); } }
in example included 3 more typical extensions. you'd have dozens or hundreds of them. (you may prefer group them in different handyextensions
files - file name of wrapper class totally irrelevant.) every engineer , team has own "common extensions" use time.
note here example example asking tricky question in category beyond me. (thank goodness ericl there!) way in most/some/older languages call "category". in c# "extension", people either "category" or "extension" time.
as say, use these in unity. cheers
if sort of thing, here's beautiful one:
// unbelievably useful array handling category games! public static t anyone<t>(this t[] ra) t:class { int k = ra.length; int r = unityengine.random.range(0,k); return ra[r]; }
Comments
Post a Comment