【发布时间】:2018-02-23 19:52:37
【问题描述】:
我正在尝试从检查器中创建一组公共游戏对象变量。我在理解如何使用变量“i”作为数组的索引时遇到问题。我收到一个错误提示 value expected,但我不确定是否应该将“i”变量添加到我的索引中,例如:ThingToKill[i].SetActive(true);。
如果我想要游戏对象,我可以让它工作的唯一方法是在数字中硬编码,例如这个ThingToKill[1].SetActive(true); 将允许我影响 2 个游戏对象。
这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class publicarray : MonoBehaviour
{
public GameObject[] ThingToKill;
public float startAfterThisManySeconds;
public float endafterThisManySeconds;
void Start()
{
ThingToKill[i].SetActive(false);
StartCoroutine("turnOn");
StartCoroutine("turnOff");
for (int i = 0; i < ThingToKill.Length; i++)
{
Debug.Log(ThingToKill[i].name);
}
}
void Update()
{
}
IEnumerator turnOn()
{
yield return new WaitForSeconds(startAfterThisManySeconds);
StartCoroutine("on");
Debug.Log("on");
}
IEnumerator turnOff()
{
yield return new WaitForSeconds(endafterThisManySeconds + startAfterThisManySeconds);
StartCoroutine("off");
Debug.Log("off");
}
IEnumerator on()
{
ThingToKill[].SetActive(true);
yield return new WaitForSeconds(.000001f);
}
IEnumerator off()
{
ThingToKill[].SetActive(false);
yield return new WaitForSeconds(.000001f);
}
}
编辑这是有效的解决方案:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class publicarray : MonoBehaviour
{
public GameObject[] ThingToKill;
public float startAfterThisManySeconds;
public float endafterThisManySeconds;
void Start()
{
for (int i = 0; i < ThingToKill.Length; i++)
{
Debug.Log(ThingToKill[i].name);
ThingToKill[i].SetActive(false);
StartCoroutine("turnOn");
StartCoroutine("turnOff");
}
}
void Update()
{
}
IEnumerator turnOn()
{
yield return new WaitForSeconds(startAfterThisManySeconds);
StartCoroutine("on");
Debug.Log("on");
}
IEnumerator turnOff()
{
yield return new WaitForSeconds(endafterThisManySeconds + startAfterThisManySeconds);
StartCoroutine("off");
Debug.Log("off");
}
IEnumerator on()
{
for (int i = 0; i < ThingToKill.Length; i++)
{
ThingToKill[i].SetActive(true);
yield return new WaitForSeconds(.000001f);
}
}
IEnumerator off()
{
for (int i = 0; i < ThingToKill.Length; i++)
{
ThingToKill[i].SetActive(false);
yield return new WaitForSeconds(.000001f);
}
}
}
【问题讨论】:
-
非常酷,我没有意识到您可以通过检查器使用动态数组,我将不得不使用它。数组的更多字段是否会自动添加到检查器中以在您添加它们时容纳更多对象,或者您是否在检查器中有一个字段来指定您希望数组有多大?
-
@StephenDocy - 会自动创建更多字段,非常方便。如果您使用此脚本,您将看到您可以更改一个名为“Size”的公共 int,它将创建您指定的任意数量的字段。