Visual studio 我得到的索引超出了数组错误的范围

Visual studio 我得到的索引超出了数组错误的范围,visual-studio,unity3d,Visual Studio,Unity3d,我不熟悉unity中的编码,我写了一些代码,这些代码告诉我索引超出了数组错误的范围,但我不知道问题出在哪里。如果你能给我一些关于我做错了什么的见解,那就太好了。这是我为一个我正在unity中工作的游戏编写的代码: using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public float

我不熟悉unity中的编码,我写了一些代码,这些代码告诉我索引超出了数组错误的范围,但我不知道问题出在哪里。如果你能给我一些关于我做错了什么的见解,那就太好了。这是我为一个我正在unity中工作的游戏编写的代码:

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

public class PlayerMovement : MonoBehaviour
{
    public float speed = 20.5f;

    public float HorizontalInput;

    public float xrange = 16;
    public GameObject[] projectileprefab;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            **//This is the broken line of code**
            int ProjectileIndex = Random.Range(0, projectileprefab.Length);
            Instantiate(projectileprefab[ProjectileIndex], transform.position, transform.rotation);





        }

        transform.Translate(Vector3.right * Time.deltaTime * speed * HorizontalInput);
        HorizontalInput = Input.GetAxis("Horizontal");
        if (transform.position.x < -xrange)
        {
            transform.position = new Vector3(-xrange, transform.position.y, transform.position.z);
        }
        if (transform.position.x > xrange)
        {
            transform.position = new Vector3(xrange, transform.position.y, transform.position.z);
        }

    }
}
使用系统集合;
使用System.Collections.Generic;
使用UnityEngine;
公共类玩家运动:单一行为
{
公共浮子速度=20.5f;
公共浮动水平输入;
公共浮动范围=16;
公共游戏对象[]projectleprefab;
//在第一帧更新之前调用Start
void Start()
{
}
//每帧调用一次更新
无效更新()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
**//这是代码的断行**
int projectleIndex=Random.Range(0,projectleprefab.Length);
实例化(projectleprefab[projectleIndex],transform.position,transform.rotation);
}
transform.Translate(Vector3.right*Time.deltaTime*速度*水平输入);
HorizontalInput=Input.GetAxis(“水平”);
if(变换位置x<-x范围)
{
transform.position=新矢量3(-xrange,transform.position.y,transform.position.z);
}
if(变换位置x>x范围)
{
transform.position=新矢量3(xrange,transform.position.y,transform.position.z);
}
}
}
问题是:

      int ProjectileIndex = Random.Range(0, projectileprefab.Length);
      Instantiate(projectileprefab[ProjectileIndex], transform.position, transform.rotation)
ProjectlePreFab的长度为零,因此它实例化了第一个对象,但其为空。解决方案:在inspector中,您可以设置ProjectleRefab数组的长度并为其分配游戏对象。

我只需删除一行//这是编辑器中代码和游戏对象的虚线,您的代码在我的游戏中运行良好,没有错误:)