• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by hynra · Feb 26, 2014 at 05:51 AM · 2d

UnityException: Index out of bounds

I Have script to control main character ini unity 2D platformer, since i implement touch control in that script, i got error message like UnityException: Index out of bounds.

Here the line i got error :

 void Update ()
 {
     int k = 0;
     //------------------------------------------- left right touch
      
     // Loop over every touch found
     anim.SetFloat("Speed", Mathf.Abs(Input.GetTouch(k).position.x));
     while (k < Input.touchCount) 
     {    
         // Is this the beginning phase of the touch?
         if (Input.GetTouch(k).phase == TouchPhase.Began)    
         {
             // Does the touch happens on the right side of the screen?
             if (Input.GetTouch(k).position.x < w / 2 && Input.GetTouch(k).position.y > h / 3 ) {    
                 // Move your character right
                 moveToRight();
             }
             // Does the touch happens on the left side of the screen?
             if (Input.GetTouch(k).position.x > w / 2 && Input.GetTouch(k).position.y > h / 3){ 
                 // Move your character left
                 moveToLeft();
             }
         }
         ++k;
     }
     transform.position += transform.right*Input.GetTouch(k).position.x*speed*Time.deltaTime;}


How can i resolve this ?

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image GambinoInd · Feb 26, 2014 at 06:01 AM 0
Share

It looks like an issue with the variable k. I'm not entirely sure about this, but first I would change ++k; to k++;

Second thing I would try is debugging by using Debug.log("$$anonymous$$:"+k+" Touch Count:"+Input.touchCount);

I would put that directly under while (k < Input.touchCount) {

if the touch count is 2, the highest k should ever go is 1.

avatar image hynra · Feb 26, 2014 at 11:35 AM 0
Share

Yep, i have tried your suggest, but still Index out of bounds on line 7 and 26. Is it wrong implement of my touch logic or something ?

3 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Ebil · Feb 26, 2014 at 11:47 AM

You check for Input.GetTouch(k) at the beginning, without checking if k has a 0 value. I think its null or so if no touch is happening. 0 would be the first finger touch.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image hynra · Feb 26, 2014 at 12:32 PM 0
Share

So, what should i do ?

avatar image Ebil · Feb 27, 2014 at 12:56 PM 1
Share

check for Input.touchCount > 0

avatar image mrthang · Oct 12, 2017 at 04:11 AM 0
Share

Please help me!
http://answers.unity3d.com/questions/1419236/joystickcontroller-not-work.html

avatar image
2

Answer by robertbu · Feb 26, 2014 at 05:58 AM

In the future it would be helpful if did a copy and paste of the error message from the console. Knowing the line number and other info in the error message is often very helpful.

In your case, I'm betting that your error is on line 26. You look through all the touch positions incrementing 'k' each time through the 'while' loop. The 'while' loop exits when 'k' is out of bounds for 'touchCount. So when you use it on line 26, you are passing a 'k' one higher than can be used in GetTouch(). I'm not sure of the fix, since I only have a section of your code. Calling it with 'k-1' should work:

  transform.position += transform.right*Input.GetTouch(k-1).position.x*speed*Time.deltaTime;}
Comment
Add comment · Show 8 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image hynra · Feb 26, 2014 at 11:37 AM 0
Share

Yep, i have tried your suggest too, but still Index out of bounds on line 7 and 26. Is it wrong implement of my touch logic or something ?

avatar image robertbu · Feb 26, 2014 at 04:12 PM 0
Share

@Ebil is right. You need to not execute lines 26 and 7 if Input.touchCount is 0.

avatar image hynra · Feb 27, 2014 at 01:12 AM 0
Share

Ok. so, how to check if k has value 0 in Update() function ?

avatar image robertbu · Feb 27, 2014 at 01:24 AM 0
Share

Something like:

 if ( Input.touchCount > 0) {
     anim.SetFloat("Speed", $$anonymous$$athf.Abs(Input.GetTouch(k).position.x));
 }

There may be a cleaner approach to the problem. Without more of your code and some context, I cannot say if your approach here is is a good one, but checking for 'touchCount' greater than 0 should get rid of your null reference exceptions.

avatar image hynra · Feb 28, 2014 at 02:00 AM 0
Share

Awesome! it's work with check Input.touchCount > 0 Thanks for your help. but, i got little problem, when i try move the player, the player not move, i'm sure the problem because transform.position += transform.right*Input.GetTouch(k).position.x*speed*Time.deltaTime;} not setting perfectly, any suggestion ?

Show more comments
avatar image
0

Answer by mrthang · Oct 10, 2017 at 10:26 AM

 using UnityEngine;
 using System.Collections;
 using UnityEngine.EventSystems;
 using UnityEngine.UI;
 
 public class JoystickController : MonoBehaviour,IPointerUpHandler,IPointerDownHandler {
 
     public ControllerInput tankPlayer;
     public float offset = 35.0f;
 
     public Sprite button_not_touch;
     public Sprite button_touch;
 
     public Image[] imageButtons;
 
     private bool isTouch;
     private Vector3 deltaVector;
 
     void Update()
     {
         // When touch, process touch postion
         if (isTouch) {
 
             // Check touch, if have mutiple touch
             Touch[] myTouchs = Input.touches;
             Vector3 touchPos = Vector3.zero;
 
             if (myTouchs.Length > 1)
             {
                 for (int i = 0; i < myTouchs.Length; i++)
                 {
                     if (myTouchs[i].position.y < transform.position.y * 2 && myTouchs[i].position.x < transform.position.x * 2)
                     {
                         touchPos = myTouchs[i].position;
                         break;
                     }
                 }
                 deltaVector = touchPos - transform.position;
             }
             else
                 deltaVector = (Vector3)Input.GetTouch(0).position - transform.position;
                
             // Process when magnitude delta vector greater than 25
             if (Vector3.Magnitude (deltaVector) > 25.0f) {
                 if (Mathf.Abs (deltaVector.x) > Mathf.Abs (deltaVector.y)) {
                     // Move horizontal
                     if (deltaVector.x > offset) {
                         tankPlayer.MoveRight ();
                         ButtonHit (3);
                     } else if (deltaVector.x < -offset) {
                         tankPlayer.MoveLeft ();
                         ButtonHit (1);
                     }
                 } else {
                     // Move vertical
                     if (deltaVector.y > offset) {
                         tankPlayer.MoveUp ();
                         ButtonHit (0);
                     } else if (deltaVector.y < -offset) {
                         tankPlayer.MoveDown ();
                         ButtonHit (2);
                     }
                 }
             } else
                 tankPlayer.Release ();
         } else
             tankPlayer.Release ();
     }
 
     // Method to change button sprites
     void ButtonHit(int indexTouch)
     {
         foreach(Image image in imageButtons)
             image.sprite = button_not_touch;
     
 
         imageButtons[indexTouch].sprite = button_touch;
     }
 
     // Event handle when touch to joystick
     public void OnPointerUp(PointerEventData eventData )
     {
 
         foreach(Image image in imageButtons)
             image.sprite = button_not_touch;
 
         isTouch = false;
     }
 
     // Event handle when touch to joystick
     public void OnPointerDown(PointerEventData eventData)
     {
         isTouch = true;
     }
 
     void OnDisable()
     {
         tankPlayer.Release();
     }
 }
 
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image mrthang · Oct 10, 2017 at 10:27 AM 0
Share

it is error line 41 deltaVector = (Vector3)Input.GetTouch(0).position - transform.position; please help me.thanks for all you.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

23 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

A node in a childnode? 1 Answer

Bounce value not change in script for 2D object in Unity4.3. 1 Answer

2D Animation does not start 1 Answer

Make 2d Animation Scene 0 Answers

Unity 2D, Ignore impact force 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges