c# - Max array range limit -
i'm working on code 2d game player has 3 hearts.
if player collides bombprefab, loses 1 heart. if player collides heartprefab, wins heart. if collides 3 consecutive times bombprefab, game ends.
the hearts texture follows. array 0 (3 hearts) array 1 (2 hearts) array 2 (1 heart).
i having problem limiting array! want know how following response: if player has 3 hearts , collides heartprefab, object destroyed, there no change in number of hearts player has.
the code below works take , give hearts. when collide 1 heartprefab, , have 3 hearts (maximum) error: index out range array.
how should proceed? c# answer if possible
using unityengine; using system.collections; using unityengine; using system.collections; public class heart : monobehaviour { public texture2d[] initialheart; private int heart; private int manyheart; void start () { // game start 3 hearts @ range 0 getcomponent<guitexture> ().texture = initialheart [0]; heart = initialheart.length; } void update () { } public bool takehearts () { if (heart < 0) { return false; } if (manyheart < (heart - 1)) { manyheart += 1; getcomponent<guitexture> ().texture = initialheart [manyheart]; return true; } else { return false; } } public bool addhearts () { if (heart <= 2) { return false; } if (manyheart < (heart + 1)) { manyheart -= 1; getcomponent<guitexture> ().texture = initialheart [manyheart]; return true; } else { return false; } } }
you overcomplicating if statements (unless there other reason doing so)... var manyheart , heart inversely related. use:
public bool addhearts () { if (manyheart > 0) { manyheart -= 1; getcomponent<guitexture> ().texture = initialheart [manyheart]; return true; } else { return false; } }
Comments
Post a Comment