为什么我会得到null或索引超出范围? [重复]

问题描述 投票:0回答:1

在这种情况下,动画师包含3个项目。但是,我不知道有多少个物品。可以是3或30。我可以很好地获得“ medea_m_arrebola”索引,但是如何获取其余索引?

我也在这行上尝试过2次,现在尝试了1次:但是却获得异常IndexOutOfRangeException:索引超出了数组的范围。

soldiers_indexs = new int[1];

如果不使用此行,我将在该行中获取null:

soldiers_indexs[i] = i;

如何获得其余项目的索引?

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OpenningScene : MonoBehaviour
{
    [Header("Animators")]
    public Animator[] animators;
    [Space(5)]
    [Header("Movement Settings")]
    public Transform target;
    public float movingSpeed = 1f;
    public bool slowDown = false;
    [Space(5)]
    [Header("Rotation Settings")]
    public float rotationSpeed;
    public DepthOfField dephOfField;
    public float waitingAnimation;
    public float startConversation;

    private Vector3 targetCenter;
    private bool startWaitingAnim = true;
    private bool endRot = false;
    private int medea_m_arrebola_index;
    private int[] soldiers_indexs;

    // Use this for initialization
    void Start()
    {
        targetCenter = target.GetComponent<Renderer>().bounds.center;
        soldiers_indexs = new int[1];
        for (int i = 0; i < animators.Length; i++)
        {
            animators[i].SetFloat("Walking Speed", movingSpeed);

            if(animators[i].name == "medea_m_arrebola")
            {
                medea_m_arrebola_index = i;
            }
            else
            {
                soldiers_indexs[i] = i;
            }
        }
    }
c# unity3d
1个回答
0
投票

因为C#不是Java语言。

您的带有soldiers_indexs[i] = i;的代码将在Javascript中完美运行,即使最终结果难以理解。但是,C类型语言的数组是定义的数据结构,具有上下限。 C#不允许您执行似乎毫无意义的操作。

由于您的代码尚不清楚您要执行的操作,因此我不建议您使用前进路径。但是,很明显,使用索引变量i引用数组中您没有迭代的位置是一个错误。]

[通常,在C#中,我们使用更多的通用数据结构,例如List<T>。另外,我不建议使用List<T>循环。 for循环几乎总是更有意义,而且总是更容易阅读。

© www.soinside.com 2019 - 2024. All rights reserved.