[英]SetActive Random object Unity 2d
我想在 Step 脚本中通过 Random 对其进行 SetActive 1 索引。 而Count=2,Random会继续显示,但是不起作用。
我的代码:
public class Step
{
public string stepName;
public GameObject[] objects;
}
public void AddCount()
{
Count++;
if (Count == 2)
{
nextStep();
Count = 0;
}
}
public void nextStep()
{
for (int i = 0; i < _steps.Count; i++)
{
int ranI = Random.Range(0, _steps.Count - 1);
_steps[ranI].objects[i].SetActive(true);
}
}
谢谢
您确定每个步骤至少包含与_steps
列表本身中的步骤一样多的对象......?
访问
_steps[ranI].objects[i]
在我眼里毫无意义。
听起来您更想要的是选择一个随机步骤,然后启用所有相应的对象。
为了同时禁用当前步骤,我会保留该信息,例如
// Stores which step is currently being displayed so we can hide it later
private int? currentStepIndex;
public void nextStep()
{
// if there is currently a step displayed
if(currentStepIndex != null)
{
// hide all that step's objects
var step = _steps[currentStepIndex];
foreach(var obj in step.objects)
{
obj.SetActive(false);
}
}
// pick a random step
// Note that the upper index already is exclusive
// => this will return valid indices between 0 and _steps.Count - 1 now
currentStepIndex = Random.Range(0, _steps.Count);
var nextStep = _steps[currentStepIndex];
// enable all that step's objects
foreach(var obj in nextStep.objects)
{
obj.SetActive(true);
}
}
就我个人而言,我什至会将循环抽象为Step
class 本身,例如
public class Step
{
public string stepName;
// This can be private now
[SerializeField] private GameObject[] objects;
public void SetActive(bool active)
{
foreach(var obj in objects)
{
obj.SetActive(active);
}
}
}
然后存储Step
并执行
private Step currentStep;
public void nextStep()
{
currentStep?.SetActive(false);
var currentStepIndex = Random.Range(0, _steps.Count);
currentStep = _steps[currentStepIndex];
currentStep.SetActive(true);
}
因为这样你也可以排除当前步骤,这样你就不会连续两次随机选择相同的索引。 或者甚至确保每个步骤只被选择一次,直到显示所有步骤,等等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.