Saturday, 15 September 2012

c# - Don't know how to get enemy's health -



c# - Don't know how to get enemy's health -

i have code , don't know why hit.collider.gameobject.getcomponent("health") returning null

void shoot() { vector2 mouseposition = new vector2 (camera.main.screentoworldpoint (input.mouseposition).x, camera.main.screentoworldpoint (input.mouseposition).y); vector2 firepointposition = new vector2 (firepoint.position.x, firepoint.position.y); raycasthit2d nail = physics2d.raycast (firepointposition, mouseposition - firepointposition, bulletrange, whattohit); if (time.time >= timetospawneffect) { effect (); timetospawneffect = time.time + 1/effectspawnrate; } if (hit.collider != null) { if (hit.collider.name == "enemy") { debug.log(hit.collider.gameobject.getcomponent("health")); } //debug.log("we nail " + hit.collider.name + " , did " + harm + " damage"); } }

here enemy script

using unityengine; using system.collections; public class enemyai : monobehaviour { public float health = 100f; //... rest of code }

you need reference script attached enemy. utilize script manipulate health.

find gameobject.

gameobject g = hit.collider.gameobject;

get reference script.

enemyai e = g.getcomponent<enemyai>();

manipulate health.

e.health = 0f;

in 1 line if want badass.

hit.collider.gameobject.getcomponent<enemyai>().health = 0.0f;

bonus tip: health should private , enemyai should have setter , getter variable.

c# unity3d

No comments:

Post a Comment