【问题标题】:Error CS0021: Cannot apply indexing with [] to an expression of type `UnityEngine.GameObject'错误 CS0021:无法使用 [] 将索引应用于“UnityEngine.GameObject”类型的表达式
【发布时间】:2018-09-15 06:45:28
【问题描述】:

我正在尝试使用 Unity Prefabs 进行简单的爆炸,但它一直在说

错误 CS0021:无法将带有 [] 的索引应用于“UnityEngine.GameObject”类型的表达式

我检查了代码,但找不到问题。这是我尝试过的:

public GameObject[] ParticlePrefab; 
public int amountOfPartcles = 3; 

// Use this for initialization  
void Start () 
{               
    for(int i = 0; i<amountOfPartcles; i++) 
    {
        GameObject ParticlePrefab = Instantiate(ParticlePrefab[Random.Range(0,amountOfPartcles)]);
        ParticlePrefab.transform.position = transform.position;
    }
}

【问题讨论】:

  • 核心问题是你有 两个 东西叫 ParticlePrefab - 更改其中一个的名称。
  • 为什么要重新声明 ParticlePrefab?您现在在顶部将它声明为数组,现在再次作为 Start 中的局部变量。

标签: c# unity3d


【解决方案1】:

问题是您使用了两次相同的名称 (ParticlePrefab)。

另外,你确定要以粒子数量变量来选择粒子。按照您的操作方式,如果您的 perfab 数量少于所需的粒子数量,它可能会随机崩溃。

下面是你可以如何做你的启动方法:

void Start () 
{    
    const int numberOfPrefabs = ParticlePrefab.Length;           
    for(int i = 0; i<amountOfPartcles; i++) 
    {
        GameObject particle = Instantiate(ParticlePrefab[Random.Range(0,numberOfPrefabs)]);
        particle.transform.position = transform.position;
    }
}

【讨论】:

  • 感谢它解决了索引问题,但现在它显示 Assets/Explosion.cs(12,46): error CS0133: The expression being assigned to `numberOfPrefabs' must be constant
  • 去掉常量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
  • 2018-04-03
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多