c# - How To Fix 'Array index is out of range error' In Unity3D -
i've been following block breaker section of course learn code making games (in unity 4.6.3) on udemy. decided take different path on game , challenge myself. have issues. idea when ball hits collider (named losecollider) @ bottom of screen, player lose 1 life (of there 5). can see screen shot below of game far, there 5 hearts, each sprite attached. want have ball hit losecollider , change sprite of hearts according how many times losecollider hit. keep getting error message:
here code:
using unityengine; using system.collections; using unityengine.ui; public class losecollider : monobehaviour { private levelmanager levelmanager; public sprite[] lives; public gameobject lives1; public gameobject lives2; public gameobject lives3; public gameobject lives4; public gameobject lives5; private int amounthit; private int maxhit = 5; void start () { levelmanager = gameobject.findobjectoftype<levelmanager>(); } void ontriggerenter2d (collider2d trigger) { print ("trigger"); } void oncollisionenter2d (collision2d collision) { loadsprites (); print ("collider"); amounthit++; print (amounthit); if(amounthit == maxhit){ levelmanager.loadlevel("lose"); } } void loadsprites () { int spriteindex = 1; lives1.getcomponent<spriterenderer>().sprite = lives[spriteindex]; if(amounthit >= 1){ print ("hit 1"); lives1.getcomponent<spriterenderer>().sprite = lives[spriteindex]; } else if(amounthit >= 2){ print ("hit 2"); lives2.getcomponent<spriterenderer>().sprite = lives[spriteindex]; } else if(amounthit >= 3){ print ("hit 3"); lives3.getcomponent<spriterenderer>().sprite = lives[spriteindex]; } else if(amounthit >= 4){ print ("hit 4"); lives4.getcomponent<spriterenderer>().sprite = lives[spriteindex]; } else if(amounthit >= 5){ print ("hit 5"); lives5.getcomponent<spriterenderer>().sprite = lives[spriteindex]; } }
from code:
int spriteindex = 1; lives1.getcomponent<spriterenderer>().sprite = lives[spriteindex];
have filled lives
array something? trying access array index >= size of array cause error yours. it's hard without knowing you've filled lives
array editor, i'd start setting spriteindex
0.
Comments
Post a Comment