Search Unity

IndexOutOfRangeException: Index was outside the bounds of the array.

Discussion in 'UGUI & TextMesh Pro' started by 479813005, Nov 2, 2018.

Thread Status:
Not open for further replies.
  1. 479813005

    479813005

    Joined:
    Mar 18, 2015
    Posts:
    71
  2. GiedriusUnity

    GiedriusUnity

    Unity Technologies

    Joined:
    Aug 23, 2016
    Posts:
    2
    For those stumbling onto this thread, I have since looked at the issue on our bug reporting platform:
    In C# and in most programming languages, arrays start at 0. I.e., an array of length = 1, would have an values at index = 0, an array of length = 2 would have values at index = 0 and index = 1, etc... Looking at the picture and values you pass above to the function variables, you start your for loop at the passed value of start(1), it tries to get the chars[1] value, when it only has a chars[0] value. When you call IntToString, make sure you're passing the correct value to start the loop on.
     
  3. 479813005

    479813005

    Joined:
    Mar 18, 2015
    Posts:
    71
    o_O incredible……Maybe I didn’t express it clearly.
    Will report an error when converting from the end of an array to a string。



    Or Test:
    Code (CSharp):
    1. public void Test(TextMeshProUGUI text)
    2.         {
    3.             int[] chararray = new int[] { 1, 2, 3, 4, 5 };
    4.             text.SetCharArray(chararray, 1, 1);
    5.         }
     
    Last edited: Nov 19, 2018
  4. 479813005

    479813005

    Joined:
    Mar 18, 2015
    Posts:
    71
  5. Stephan_B

    Stephan_B

    Joined:
    Feb 26, 2017
    Posts:
    6,595
    Here is a revised IntToString() function.

    Code (csharp):
    1.  
    2. public static string IntToString(this int[] unicodes, int start, int length)
    3. {
    4.     if (start > unicodes.Length)
    5.         return string.Empty;
    6.  
    7.     int end = Mathf.Min(start + length, unicodes.Length);
    8.  
    9.     char[] chars = new char[end - start];
    10.  
    11.     int writeIndex = 0;
    12.  
    13.     for (int i = start; i < end; i++)
    14.     {
    15.         chars[writeIndex++] = (char)unicodes[i];
    16.     }
    17.  
    18.     return new string(chars);
    19. }
    20.  
    This change will be in the next release of the TMP package for Unity 2018.3 and up. I will also add additional bounds check in the SetCharArray() function.
     
    Last edited: Nov 19, 2018
    479813005 likes this.
  6. a7m3d_95

    a7m3d_95

    Joined:
    Dec 26, 2018
    Posts:
    1
    i have the same issue would be thankful for any help

    this is my error message :
    IndexOutOfRangeException: Index was outside the bounds of the array.
    mobileInputs.Update () (at Assets/scripts/mobileInputs.cs:57)


    and this is the part of the code in question:
    if (Input.touches.Length != 0)
    {
    if (Input.touches[0].phase == TouchPhase.Began)
    tap = true;
    isDragging = true;
    startTouch = Input.mousePosition;
    }
    // this is where the error is //
    else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
    {
    //startTouch = swipeDelta = Vector2.zero;
    isDragging = false;
    Reset();
    }
     
  7. attis911

    attis911

    Joined:
    Dec 24, 2018
    Posts:
    1
    I have the same problem IndexOutOfRangeException: Index was outside the bounds of the array. mobileInputs.Update
    Anyone can help me out what is the problem? -- else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
     
  8. TortoRacoon

    TortoRacoon

    Joined:
    Apr 17, 2019
    Posts:
    61
    I have the same issue, I was checking a tutorial, I wrote exactly the same but the guy in the video did not have any error. WHY!

    Code (CSharp):
    1.     public Transform origin;
    2.  
    3.     public float rayLength = 13.0f;
    4.  
    5.     private void Update()
    6.     {
    7.         if (Input.GetMouseButtonDown(0))
    8.         {
    9.             RaycastHit[] hits = null;
    10.  
    11.             hits = Physics.RaycastAll(origin.position, Vector3.forward, rayLength);
    12.  
    13.             if (hits.Length > 0)
    14.             {
    15.                 for (int i = 0; i < hits.Length; i++)
    16.                 {
    17.                     if ( hits[i].collider )
    18.                     {
    19.                         Debug.Log ("Hit: " + hits[1].collider.name );
    20.                     }
    21.  
    22.                 }
    23.             }
     
  9. minerandom

    minerandom

    Joined:
    May 12, 2019
    Posts:
    6
    When I run this project on unity it keeps doing this error:
    IndexOutOfRangeException: Index was outside the bounds of the array.
    FruitSpawner+<SpawnFruits>d__5.MoveNext () (at Assets/FruitSpawner.cs:26)
    and here is my code:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class FruitSpawner : MonoBehaviour {
    public GameObject fruitPrefab;
    public Transform[] spawnPoints;
    public float minDelay = .1f;
    public float maxDelay = 1f;
    // Use this for initialization
    void Start()
    {
    StartCoroutine(SpawnFruits());
    }
    IEnumerator SpawnFruits()
    {
    while (true)
    {
    float delay = Random.Range(minDelay, maxDelay);
    yield return new WaitForSeconds(delay);
    int spawnIndex = Random.Range(0, spawnPoints.Length);
    Transform spawnPoint = spawnPoints[spawnIndex];
    GameObject spawnedFruit = Instantiate(fruitPrefab, spawnPoint.position, spawnPoint.rotation);
    Destroy(spawnedFruit, 4f);
    }
    }
    }
    can someone please tell me how to fix this. Im using unity 2019
     
  10. MrLucid72

    MrLucid72

    Joined:
    Jan 12, 2016
    Posts:
    994
    I'm having the same issue in Unity 2018.3.4f1 -

    Code (CSharp):
    1. string addStr = "";
    2.  
    3. foreach (string str in someListOfStr) // OP's err
    4. {
    5.     addStr += (str + "\n")
    6. }
    7.  
    8. // #####################################
    9.  
    10. IndexOutOfRangeException: Index was outside the bounds of the array.
    11. TMPro.TMP_Text.DrawUnderlineMesh (UnityEngine.Vector3 start, UnityEngine.Vector3 end, System.Int32& index, System.Single startScale, System.Single endScale, System.Single maxScale, System.Single sdfScale, UnityEngine.Color32 underlineColor) (at Library/PackageCache/com.unity.textmeshpro@1.3.0/Scripts/Runtime/TMP_Text.cs:5204)
    12. TMPro.TextMeshProUGUI.GenerateTextMesh () (at Library/PackageCache/com.unity.textmeshpro@1.3.0/Scripts/Runtime/TMPro_UGUI_Private.cs:3774)
    13. TMPro.TextMeshProUGUI.OnPreRenderCanvas () (at Library/PackageCache/com.unity.textmeshpro@1.3.0/Scripts/Runtime/TMPro_UGUI_Private.cs:1642)
    14. TMPro.TextMeshProUGUI.Rebuild (UnityEngine.UI.CanvasUpdate update) (at Library/PackageCache/com.unity.textmeshpro@1.3.0/Scripts/Runtime/TextMeshProUGUI.cs:209)
    15. UnityEngine.UI.CanvasUpdateRegistry.PerformUpdate () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/CanvasUpdateRegistry.cs:198)
    16. UnityEngine.Canvas:SendWillRenderCanvases() (at ?)
     
  11. Stephan_B

    Stephan_B

    Joined:
    Feb 26, 2017
    Posts:
    6,595
    Can you provide an example of the text in "someListOfStr" so I can try to reproduce this?
     
  12. KurokoTCG

    KurokoTCG

    Joined:
    Jun 30, 2019
    Posts:
    1
    I tried to create sth like snake and ladder game. Trying to learn how to use Unity. I found the exact same error and it says that the problem is on line 87. The error doesn't show up while compiling but shows up when run the program. I use Unity 2019.1.8f1 Personal.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class GameController : MonoBehaviour
    6. {
    7.     public GameObject[] diceGameObject = new GameObject[6];
    8.     public GameObject[] tokenGameObject = new GameObject[4];
    9.     private int i;
    10.     private int dice;
    11.     private int move;
    12.     private int whiteNum;
    13.     private int blueNum;
    14.     private int redNum;
    15.     private int greenNum;
    16.     private int turn;
    17.     private int firstNum;
    18.     private int lastNum;
    19.     private bool gotSix = false;
    20.     private bool ladderCheck = false;
    21.     private bool snakeCheck = false;
    22.     private bool roolDone = false;
    23.     private int[,] ladder = {{3,20},{6,14},{11,28},{15,34},{17,74},{22,37},{38,59},{49,67},{57,76},{61,78},{73,86},{81,98},{88,91}};
    24.     private int[,] snake = {{8,4},{18,1},{26,10},{39,5},{51,6},{54,36},{56,1},{60,23},{75,28},{83,45},{85,59},{90,48},{92,25},{97,87},{99,63}};
    25.  
    26.     IEnumerator Roll(){
    27.         roolDone = true;
    28.         move = 0;
    29.         do{
    30.             for(i = 1; i<=10;i++){
    31.                 dice = Random.Range(0, 5);
    32.                 diceGameObject[dice].SetActive(true);
    33.                 yield return new WaitForSecondsRealtime((float)0.1);
    34.                 diceGameObject[dice].SetActive(false);
    35.                 yield return new WaitForSecondsRealtime((float)0.1);
    36.             }
    37.             dice = Random.Range(0, 5);
    38.             dice += 1;
    39.             diceGameObject[dice].SetActive(true);
    40.             move = move + dice + 1;
    41.             if(dice == 5){
    42.                 gotSix = true;
    43.                 yield return new WaitForSecondsRealtime(3);
    44.                 diceGameObject[dice].SetActive(false);
    45.             }else{
    46.                 gotSix = false;
    47.             }
    48.         }while(gotSix == true);
    49.         yield return new WaitForSecondsRealtime(3);
    50.         diceGameObject[dice].SetActive(false);
    51.         StartCoroutine(Move());
    52.     }
    53.    
    54.     IEnumerator Move(){
    55.         i = 0;
    56.         if(turn == 0){
    57.             while(i <= move){
    58.                 whiteNum += 1;
    59.                 i++;
    60.                 yield return new WaitForSecondsRealtime((float)0.5);
    61.             }
    62.         }else if(turn == 1){
    63.             while(i <= move){
    64.                 blueNum += 1;
    65.                 i++;
    66.                 yield return new WaitForSecondsRealtime((float)0.5);
    67.             }
    68.         }else if(turn == 2){
    69.             while(i <= move){
    70.                 redNum += 1;
    71.                 i++;
    72.                 yield return new WaitForSecondsRealtime((float)0.5);
    73.             }
    74.         }else if(turn == 31){
    75.             while(i <= move){
    76.                 greenNum += 1;
    77.                 i++;
    78.                 yield return new WaitForSecondsRealtime((float)0.5);
    79.             }
    80.         }
    81.         Check();
    82.     }
    83.  
    84.     public void Check(){
    85.         i = 1;
    86.         while(i <= ladder.Length || ladderCheck == false){
    87.             if(ladder[i, 0] == whiteNum){ //this line
    88.                 whiteNum = ladder[i, 1];
    89.                 ladderCheck = true;
    90.             }
    91.             if(ladder[i, 0] == blueNum){
    92.                 blueNum = ladder[i, 1];
    93.                 ladderCheck = true;
    94.             }
    95.             if(ladder[i, 0] == redNum){
    96.                 redNum = ladder[i, 1];
    97.                 ladderCheck = true;
    98.             }
    99.             if(ladder[i, 0] == greenNum){
    100.                 greenNum = ladder[i, 1];
    101.                 ladderCheck = true;
    102.             }
    103.             i++;
    104.         }
    105.         ladderCheck = false;
    106.         i = 0;
    107.         while(i <= snake.Length || snakeCheck == false){
    108.             if(snake[i, 0] == whiteNum){
    109.                 whiteNum = snake[i, 1];
    110.                 snakeCheck = true;
    111.             }
    112.             if(snake[i, 0] == blueNum){
    113.                 blueNum = snake[i, 1];
    114.                 snakeCheck = true;
    115.             }
    116.             if(snake[i, 0] == redNum){
    117.                 redNum = snake[i, 1];
    118.                 snakeCheck = true;
    119.             }
    120.             if(snake[i, 0] == greenNum){
    121.                 greenNum = snake[i, 1];
    122.                 snakeCheck = true;
    123.             }
    124.             i++;
    125.         }
    126.         snakeCheck = false;
    127.     }
    128.  
    129.     public void RollButtonOnClick(){
    130.         if(roolDone == false){
    131.             StartCoroutine(Roll());
    132.         }
    133.     }
    134.  
    135.     // Start is called before the first frame update
    136.     void Start()
    137.     {
    138.         print(snake);
    139.         whiteNum = blueNum = redNum = greenNum = 0;
    140.         turn = 0;
    141.         tokenGameObject[1].transform.position = new Vector3(-300,-200,0);
    142.     }
    143.  
    144.     // Update is called once per frame
    145.     void Update()
    146.     {
    147.         lastNum = (int)(whiteNum - Mathf.Floor(whiteNum / 10));
    148.         firstNum = (int)(Mathf.Floor(whiteNum / 10));
    149.         if((whiteNum <= 10 && whiteNum >= 1)|| (whiteNum >= 21 && whiteNum <= 30) || (whiteNum >= 41 && whiteNum <= 50) || (whiteNum >= 61 && whiteNum <= 70) || (whiteNum >= 81 && whiteNum <= 90)){
    150.             tokenGameObject[1].transform.position = new Vector3((-396 + (firstNum * 72)),(-44 + (firstNum * 72)),0);
    151.         }else if((whiteNum <= 20 && whiteNum >= 11)|| (whiteNum >= 31 && whiteNum <= 40) || (whiteNum >= 51 && whiteNum <= 69) || (whiteNum >= 71 && whiteNum <= 80) || (whiteNum >= 91 && whiteNum <= 100)){
    152.             tokenGameObject[1].transform.position = new Vector3((396 - (firstNum * 72)),(-44 + (firstNum * 72)),0);
    153.         }
    154.     }
    155. }
     
  13. MrLucid72

    MrLucid72

    Joined:
    Jan 12, 2016
    Posts:
    994
    Sadly, I forgot where this happened. I tried to check out the stacktrace, but sadly, Unity's stacktraces can often be incredibly useless (such as this instance): It traced only to Unity files and didn't even trace back to my own file o_O otherwise I would've been happy to show the git diff (I used an arbitrary example).
     
  14. MrLucid72

    MrLucid72

    Joined:
    Jan 12, 2016
    Posts:
    994
    Actually, I remember the source:

    upload_2019-7-1_11-2-0.png

    Code (CSharp):
    1. [
    2.     "test memo --5b23cb630d413804dae5945b",
    3.     "some other memo test --xbprev"
    4. ]
    75% sure it was that ^ but 25% could've been this:

    Code (CSharp):
    1. [
    2.     "test memo --kiroprev2",
    3.     "test memo 2 --kiroprev2",
    4.     "blah blah --",
    5.     "test test --kiroprev2",
    6.     "test test 2 & and sign = and equals sign! --kiroprev2",
    7.     "test 3  --Unknown (pid==5b23cb630d413804dae5945b)",
    8.     "test 4  --5b23cb630d413804dae5945b"
    9. ]
     
  15. scarnj

    scarnj

    Joined:
    Jan 28, 2019
    Posts:
    1
    upload_2019-10-22_10-51-56.png Im pretty new to coding and im at a loss. Ive increased and decreased the range value top and bottom several times. Can seem to get past IndexOutOfRangeException error
     
  16. Squidylad

    Squidylad

    Joined:
    Mar 3, 2020
    Posts:
    1
    I'd like to new if anyone has found a solution to this issue. I too im reciveing the messages Capture.PNG Capture.PNG Capture.PNG
     
  17. SuperPox

    SuperPox

    Joined:
    Apr 29, 2020
    Posts:
    12
    lol guess we all are screwed. having the same problem
     
  18. nurfatinhamdan111

    nurfatinhamdan111

    Joined:
    Feb 12, 2019
    Posts:
    1
    upload_2020-5-6_22-53-40.png

    Hello! I am new to Unity and C#. I am stucked here and really dont know what to do. This is a simple jigsaw puzzle for my study project. Please help me :'( Anyone know the solution? Can anyone teach me how to solve it? Please :'(
     
    MadEmpress7 likes this.
  19. arikalobbia

    arikalobbia

    Joined:
    May 21, 2020
    Posts:
    1
    i have no idea lol im new help
    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using UnityStandardAssets.CrossPlatformInput;
    4. using UnityStandardAssets.Utility;
    5. using Random = UnityEngine.Random;
    6.  
    7. namespace UnityStandardAssets.Characters.FirstPerson
    8. {
    9.     [RequireComponent(typeof (CharacterController))]
    10.     [RequireComponent(typeof (AudioSource))]
    11.     public class FirstPersonController : MonoBehaviour
    12.     {
    13.         [SerializeField] private bool m_IsWalking;
    14.         [SerializeField] private float m_WalkSpeed;
    15.         [SerializeField] private float m_RunSpeed;
    16.         [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
    17.         [SerializeField] private float m_JumpSpeed;
    18.         [SerializeField] private float m_StickToGroundForce;
    19.         [SerializeField] private float m_GravityMultiplier;
    20.         [SerializeField] private MouseLook m_MouseLook;
    21.         [SerializeField] private bool m_UseFovKick;
    22.         [SerializeField] private FOVKick m_FovKick = new FOVKick();
    23.         [SerializeField] private bool m_UseHeadBob;
    24.         [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
    25.         [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
    26.         [SerializeField] private float m_StepInterval;
    27.         [SerializeField] private AudioClip[] m_FootstepSounds;    // an array of footstep sounds that will be randomly selected from.
    28.         [SerializeField] private AudioClip m_JumpSound;           // the sound played when character leaves the ground.
    29.         [SerializeField] private AudioClip m_LandSound;           // the sound played when character touches back on ground.
    30.  
    31.         private Camera m_Camera;
    32.         private bool m_Jump;
    33.         private float m_YRotation;
    34.         private Vector2 m_Input;
    35.         private Vector3 m_MoveDir = Vector3.zero;
    36.         private CharacterController m_CharacterController;
    37.         private CollisionFlags m_CollisionFlags;
    38.         private bool m_PreviouslyGrounded;
    39.         private Vector3 m_OriginalCameraPosition;
    40.         private float m_StepCycle;
    41.         private float m_NextStep;
    42.         private bool m_Jumping;
    43.         private AudioSource m_AudioSource;
    44.  
    45.         // Use this for initialization
    46.         private void Start()
    47.         {
    48.             m_CharacterController = GetComponent<CharacterController>();
    49.             m_Camera = Camera.main;
    50.             m_OriginalCameraPosition = m_Camera.transform.localPosition;
    51.             m_FovKick.Setup(m_Camera);
    52.             m_HeadBob.Setup(m_Camera, m_StepInterval);
    53.             m_StepCycle = 0f;
    54.             m_NextStep = m_StepCycle/2f;
    55.             m_Jumping = false;
    56.             m_AudioSource = GetComponent<AudioSource>();
    57.             m_MouseLook.Init(transform , m_Camera.transform);
    58.         }
    59.  
    60.  
    61.         // Update is called once per frame
    62.         private void Update()
    63.         {
    64.             RotateView();
    65.             // the jump state needs to read here to make sure it is not missed
    66.             if (!m_Jump)
    67.             {
    68.                 m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
    69.             }
    70.  
    71.             if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
    72.             {
    73.                 StartCoroutine(m_JumpBob.DoBobCycle());
    74.                 PlayLandingSound(m_LandSound);
    75.                 m_MoveDir.y = 0f;
    76.                 m_Jumping = false;
    77.             }
    78.             if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
    79.             {
    80.                 m_MoveDir.y = 0f;
    81.             }
    82.  
    83.             m_PreviouslyGrounded = m_CharacterController.isGrounded;
    84.         }
    85.  
    86.  
    87.         private void PlayLandingSound()
    88.         {
    89.             m_AudioSource.clip = m_LandSound;
    90.             m_AudioSource.Play(m_LandSound);
    91.             m_NextStep = m_StepCycle + .5f;
    92.         }
    93.  
    94.  
    95.         private void FixedUpdate()
    96.         {
    97.             float speed;
    98.             GetInput(out speed);
    99.             // always move along the camera forward as it is the direction that it being aimed at
    100.             Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
    101.  
    102.             // get a normal for the surface that is being touched to move along it
    103.             RaycastHit hitInfo;
    104.             Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
    105.                                m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
    106.             desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
    107.  
    108.             m_MoveDir.x = desiredMove.x*speed;
    109.             m_MoveDir.z = desiredMove.z*speed;
    110.  
    111.  
    112.             if (m_CharacterController.isGrounded)
    113.             {
    114.                 m_MoveDir.y = -m_StickToGroundForce;
    115.  
    116.                 if (m_Jump)
    117.                 {
    118.                     m_MoveDir.y = m_JumpSpeed;
    119.                     PlayJumpSound(m_JumpSound);
    120.                     m_Jump = false;
    121.                     m_Jumping = true;
    122.                 }
    123.             }
    124.             else
    125.             {
    126.                 m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
    127.             }
    128.             m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
    129.  
    130.             ProgressStepCycle(speed);
    131.             UpdateCameraPosition(speed);
    132.  
    133.             m_MouseLook.UpdateCursorLock();
    134.         }
    135.  
    136.  
    137.         private void PlayJumpSound()
    138.         {
    139.             m_AudioSource.clip = m_JumpSound;
    140.             m_AudioSource.Play(m_JumpSound);
    141.         }
    142.  
    143.  
    144.         private void ProgressStepCycle(float speed)
    145.         {
    146.             if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
    147.             {
    148.                 m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
    149.                              Time.fixedDeltaTime;
    150.             }
    151.  
    152.             if (!(m_StepCycle > m_NextStep))
    153.             {
    154.                 return;
    155.             }
    156.  
    157.             m_NextStep = m_StepCycle + m_StepInterval;
    158.  
    159.             PlayFootStepAudio(m_FootstepSounds);
    160.         }
    161.  
    162.  
    163.         private void PlayFootStepAudio(m_FootstepSounds)
    164.         {
    165.             if (!m_CharacterController.isGrounded)
    166.             {
    167.                 return;
    168.             }
    169.             // pick & play a random footstep sound from the array,
    170.             // excluding sound at index 0
    171.             int n = Random.Range(1, m_FootstepSounds.Length);
    172.             m_AudioSource.clip = m_FootstepSounds[1];
    173.             m_AudioSource.PlayOneShot(m_AudioSource.clip);
    174.             // move picked sound to index 0 so it's not picked next time
    175.             m_FootstepSounds[0] = m_FootstepSounds[0];
    176.             m_FootstepSounds[0] = m_AudioSource.clip;
    177.         }
    178.  
    179.  
    180.         private void UpdateCameraPosition(float speed)
    181.         {
    182.             Vector3 newCameraPosition;
    183.             if (!m_UseHeadBob)
    184.             {
    185.                 return;
    186.             }
    187.             if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
    188.             {
    189.                 m_Camera.transform.localPosition =
    190.                     m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
    191.                                       (speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
    192.                 newCameraPosition = m_Camera.transform.localPosition;
    193.                 newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
    194.             }
    195.             else
    196.             {
    197.                 newCameraPosition = m_Camera.transform.localPosition;
    198.                 newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
    199.             }
    200.             m_Camera.transform.localPosition = newCameraPosition;
    201.         }
    202.  
    203.  
    204.         private void GetInput(out float speed)
    205.         {
    206.             // Read input
    207.             float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
    208.             float vertical = CrossPlatformInputManager.GetAxis("Vertical");
    209.  
    210.             bool waswalking = m_IsWalking;
    211.  
    212. #if !MOBILE_INPUT
    213.             // On standalone builds, walk/run speed is modified by a key press.
    214.             // keep track of whether or not the character is walking or running
    215.             m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
    216. #endif
    217.             // set the desired speed to be walking or running
    218.             speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
    219.             m_Input = new Vector2(horizontal, vertical);
    220.  
    221.             // normalize input if it exceeds 1 in combined length:
    222.             if (m_Input.sqrMagnitude > 1)
    223.             {
    224.                 m_Input.Normalize();
    225.             }
    226.  
    227.             // handle speed change to give an fov kick
    228.             // only if the player is going to a run, is running and the fovkick is to be used
    229.             if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
    230.             {
    231.                 StopAllCoroutines();
    232.                 StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
    233.             }
    234.         }
    235.  
    236.  
    237.         private void RotateView()
    238.         {
    239.             m_MouseLook.LookRotation (transform, m_Camera.transform);
    240.         }
    241.  
    242.  
    243.         private void OnControllerColliderHit(ControllerColliderHit hit)
    244.         {
    245.             Rigidbody body = hit.collider.attachedRigidbody;
    246.             //dont move the rigidbody if the character is on top of it
    247.             if (m_CollisionFlags == CollisionFlags.Below)
    248.             {
    249.                 return;
    250.             }
    251.  
    252.             if (body == null || body.isKinematic)
    253.             {
    254.                 return;
    255.             }
    256.             body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
    257.         }
    258.     }
    259. }
    260.  
     
    shariful1 likes this.
  20. justinmatthew419

    justinmatthew419

    Joined:
    Jul 6, 2020
    Posts:
    2
    I'm new to this all together, so I'm following the 2D RPG project, and encountered this error as well. Everything was going smoothly until the dialogue section. Followed the section of the tutorial step by step and upon trying to test it in play no dialogue popped up, but the error occurred. I even thought that maybe it was just some sort of bug with the NPC prefab so I took the sprite and added all of the components to it to make it an NPC and the issue still remained.
     
  21. Flavelius

    Flavelius

    Joined:
    Jul 8, 2012
    Posts:
    945
    OutOfRangeExceptions happened to me when the component wasn't able to generate the glyph meshes somehow for some reason. It seemed to be linked to layout groups, the strange frame delayed rebuild of the UI that causes layouted rects to be zero in size at first and some other magic internals; atleast that's what researching similar issues made me start to believe.
    Sometimes rearranging the layoutgroups or using different ways of layouting served as workarounds where it was possible.
    The ContentSizeFitter component often was the source of different other problems and i think not using it fixed some of those situations too.
     
    Novack likes this.
  22. gagac42

    gagac42

    Joined:
    Apr 24, 2018
    Posts:
    119
    hello i have problem IndexOutOfRangeException: Index was outside the bounds of the array.
    pls you know fix the problem? here is my script


    Code (CSharp):
    1. public class StavZapasov : MonoBehaviour
    2. {
    3.     public string[] readText ;
    4.     public Text[] StavZapasovText ;
    5.     public string getURL = "http://LoadText.php";
    6.  
    7.  
    8.  
    9.     private void Start()
    10.     {
    11.         StartCoroutine(GetTheText());
    12.      
    13.  
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     IEnumerator GetTheText()
    18.     {
    19.         string URL = getURL;
    20.         WWW www = new WWW(URL);
    21.         yield return www;
    22.  
    23.        
    24.  
    25.         for (int i = 0; i< 27; i++)
    26.         {
    27.            
    28.  
    29.             readText = www.text.Split(System.Environment.NewLine[i]);
    30.             StavZapasovText[i].text = readText[i];
    31.          
    32.         }
    33.      
    34.        
    35.     }
    36.  
    37. }
     
    Last edited: Aug 8, 2020
  23. Flavelius

    Flavelius

    Joined:
    Jul 8, 2012
    Posts:
    945
    That's a totally unrelated problem. And this code snipped potentially has many problems.
    If you want to read every line returned, just split the text and iterate over the result.
     
  24. Nachman

    Nachman

    Joined:
    Oct 22, 2013
    Posts:
    26
    OK I hope this helps, I had the same problem, my solution:
    Select the object that has the script attached, in my case my array is public and you should make yours public too just spot the value to change. So go on the Inspector and check the array. There is a variable called "Size" which seems to take space with in the array and which I don't know were it comes from because I didn't declare it. Just increment the value of this "Size" variable by one.

    Weird...
     
    IogSotot and Rob78 like this.
  25. GAURAVJPLAYZ

    GAURAVJPLAYZ

    Joined:
    Jan 19, 2021
    Posts:
    2
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Player : MonoBehaviour
    {
    public int id;
    public string username;
    public CharacterController controller;
    public Transform shootOrigin;
    public float gravity = -9.81f;
    public float moveSpeed = 5f;
    public float jumpSpeed = 5f;
    public float health;
    public float maxHealth = 100f;







    private bool[] inputs;
    private float yVelocity = 0;

    private void Start()
    {

    gravity *= Time.fixedDeltaTime * Time.fixedDeltaTime;
    moveSpeed *= Time.fixedDeltaTime;
    jumpSpeed *= Time.fixedDeltaTime;
    }

    public void Initialize(int _id, string _username)
    {
    id = _id;
    username = _username;
    health = maxHealth;

    inputs = new bool[5];
    }

    /// <summary>Processes player input and moves the player.</summary>
    public void FixedUpdate()
    {
    if (health <= 0f)
    {
    return;
    }


    Vector2 _inputDirection = Vector2.zero;
    if (inputs[0])
    {
    _inputDirection.y += 1;
    }
    if (inputs[1])
    {
    _inputDirection.y -= 1;
    }
    if (inputs[2]) //HERE IS THE PROBLEM
    {
    _inputDirection.x -= 1;
    }
    if (inputs[3])
    {
    _inputDirection.x += 1;
    }

    Move(_inputDirection);
    }

    /// <summary>Calculates the player's desired movement direction and moves him.</summary>
    /// <param name="_inputDirection"></param>
    private void Move(Vector2 _inputDirection)
    {

    Vector3 _moveDirection = transform.right * _inputDirection.x + transform.forward * _inputDirection.y;
    _moveDirection *= moveSpeed;

    if (controller.isGrounded)
    {
    yVelocity = 0f;
    if (inputs[4])
    {
    yVelocity = jumpSpeed;
    }
    }
    yVelocity += gravity;

    _moveDirection.y = yVelocity;
    controller.Move(_moveDirection);

    ServerSend.PlayerPosition(this);
    ServerSend.PlayerRotation(this);
    }

    /// <summary>Updates the player input with newly received input.</summary>
    /// <param name="_inputs">The new key inputs.</param>
    /// <param name="_rotation">The new rotation.</param>
    public void SetInput(bool[] _inputs, Quaternion _rotation)
    {
    inputs = _inputs;
    transform.rotation = _rotation;
    }

    public void Shoot(Vector3 _viewDirection)
    {
    if (Physics.Raycast(shootOrigin.position, _viewDirection, out RaycastHit _hit, 25f))
    {
    if (_hit.collider.CompareTag("Player"))
    {
    _hit.collider.GetComponent<Player>().TakeDamage(50f);
    }
    }
    }

    public void TakeDamage(float _damage)
    {
    if (health <= 0f)
    {
    return;
    }

    health -= _damage;
    if (health <= 0f)
    {
    health = 0f;
    controller.enabled = false;
    transform.position = new Vector3(0f, 25f, 0f);
    ServerSend.PlayerPosition(this);
    StartCoroutine(Respawn());
    }

    ServerSend.PlayerHealth(this);
    }

    private IEnumerator Respawn()
    {
    yield return new WaitForSeconds(5f);

    health = maxHealth;
    controller.enabled = true;
    ServerSend.PlayerRespawned(this);
    }
    }

    WHAT SHOULD I DO
     
  26. rankerbaam

    rankerbaam

    Joined:
    Apr 20, 2021
    Posts:
    1
    Hey everyone, I had the same problem as most of you where you had the array length (in my situation it was a list so count if you're using a list and not array) correct, but still got the error [index out of range exception]. So this was my fix hopefully it works for you guys too. On the prefabs I was spawning, I had the script of where I was making the spawn call on attached. What I did was take them off since I only needed the script that moved the prefabs attached and that took away the error while still spawning my prefabs because I used a empty game object named "Game Manager" to spawn my prefabs. Hopefully this works for you guys, if not I'd suggest checking where all your scripts are attached and try removing the unnecessary ones and maybe the error will go away for you too. Good luck and keep on coding my fellow Unity community!
     
    ygisrael and zaplins like this.
  27. qwertypchimmy12

    qwertypchimmy12

    Joined:
    Jan 18, 2021
    Posts:
    23
    Hi everyone, please help me i have same issues. ive been try to solve this problem but still i didnt get it. the blue line problem : IndexOutOfRangeException: Index was outside the bounds of the array. i put this script in canvas because i want to loop the texture RawImage. RawImage as child under canvas. please anyone help me to settle my projects. thankyou!
     

    Attached Files:

  28. rasul1311

    rasul1311

    Joined:
    Feb 9, 2020
    Posts:
    2
    Всем привет!
    У меня такая же проблема:
    IndexOutOfRangeException: индекс находился за пределами массива.
    MapManager.Start() (в Assets/Scripts/MapManager.cs:22)
    Мой код:
    открытый класс MapManager: MonoBehaviour
    {
    открытый статический интервал countUnlockedMap = 1;

    публичный MapButtonManager[] mapButton;

    // Старт вызывается перед обновлением первого кадра
    пустое начало ()
    {

    for(int i = 0; i <transform.childCount; i++){
    если (я < countUnlockedMap) {
    transform.GetChild(i).GetComponent<Image>().sprite = mapButton .GetComponent<MapButtonManager>().unlockedIcon;
    transform.GetChild(i).GetComponent<Button>().interactable = true;
    }еще
    {
    transform.GetChild(i).GetComponent<Image>().sprite = mapButton .GetComponent<MapButtonManager>().lockedIcon;
    transform.GetChild(i).GetComponent<Button>().interactable = false;
    }
    }


    }
    }

    Помогите мне, пожалуйста
     
    Last edited: Aug 5, 2022
  29. siddharthsai100

    siddharthsai100

    Joined:
    Mar 30, 2022
    Posts:
    2
    even i have a same problem pls can anyone give the solution for this as soon as possible Screenshot (431).png Screenshot (431).png Screenshot (430).png Screenshot (432).png Screenshot (433).png Screenshot (431).png Screenshot (431).png Screenshot (433).png Screenshot (432).png Screenshot (430).png
     
  30. Calmandgetme

    Calmandgetme

    Joined:
    Sep 17, 2022
    Posts:
    2
    Just reset the Playerprefabs to clear the error
     
  31. Calmandgetme

    Calmandgetme

    Joined:
    Sep 17, 2022
    Posts:
    2
  32. Splatoonerd

    Splatoonerd

    Joined:
    Jan 6, 2023
    Posts:
    2
    I have a problem with gun fire texture, when I start playing and I click the left mouse button it pauses the game and appears the message.

    This is my code.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    public class Shoot : MonoBehaviour
    {
    [Header("Gun Settings")]
    public float fireRate = 0.1f;
    public int clipSize = 30;
    public int reservedAmmoCapacity = 270;
    bool canShoot;
    int currentAmmoInClip;
    int ammoInReserve;
    public Image muzzleFlashImage;
    public Sprite[] flashes;
    private void Start()
    {
    currentAmmoInClip = clipSize;
    ammoInReserve = reservedAmmoCapacity;
    canShoot = true;
    }
    private void Update()
    {
    if (Input.GetMouseButton(0) && canShoot && currentAmmoInClip > 0)
    {
    canShoot = false;
    currentAmmoInClip--;
    StartCoroutine(ShootGun());
    }
    else if (Input.GetMouseButton(1) && currentAmmoInClip < clipSize && ammoInReserve > 0) ;
    {
    int amountNeeded = clipSize - currentAmmoInClip;
    if(amountNeeded >= ammoInReserve)
    {
    currentAmmoInClip += ammoInReserve;
    ammoInReserve -= amountNeeded;
    }
    else
    {
    currentAmmoInClip = clipSize;
    ammoInReserve -= amountNeeded;
    }
    }
    }
    IEnumerator ShootGun()
    {
    StartCoroutine(MuzzleFlash());
    yield return new WaitForSeconds(fireRate);
    canShoot = true;
    }
    IEnumerator MuzzleFlash()
    {
    muzzleFlashImage.sprite = flashes[Random.Range(0, flashes.Length)];
    muzzleFlashImage.color = Color.white;
    yield return new WaitForSeconds(0.05f);
    muzzleFlashImage.sprite = null;
    muzzleFlashImage.color = new Color(0, 0, 0, 0);
    }
    }


    Is it fixable?
     
  33. Splatoonerd

    Splatoonerd

    Joined:
    Jan 6, 2023
    Posts:
    2
    The error is in this line.

    muzzleFlashImage.sprite = flashes[Random.Range(0, flashes.Length)];
     
  34. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    618
    This thread needs more embed screen shots.
     
  35. josiahime

    josiahime

    Joined:
    Jul 5, 2021
    Posts:
    1
    I had this problem recently and I came here to find the solution, unfortunately I didnt. After careful examination it turns out the problem was not my code, I just had not input a prefab for
    [SerializeField] GameObject[] fruitPrefab; in the inspector. It hid so simply because as opposed to the usual way of seeing it, It was there in the inspector as a LIST where I had to click "+" sign and then click and choose my prefab.
    My suggestion to you all is to simply select the object that the script is attached to, then make sure all the variables for input are there and have a valid object/prefab/whatever inside. SUBSCRIBE to B&Yond on youtube for more simple and beginnner solutions, Im starting to make videos soon.https://www.youtube.com/channel/UC46jHwm3CTZ91ozn6Bws1DQ
     
  36. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,443
    Can some moderator lock this thread? The original question was about Unicode conversions in TextMesh Pro objects, and was handled satisfactorily. Everyone else is google-confused and appending whatever Index Out Of Range errors they get here.
     
Thread Status:
Not open for further replies.