[英]Unity C# Yield WaitForSeconds within For Loop Only Works Once
[英]I have a for loop in C#, which works in conjuction with Unity engine. But how do i make it so it only calls the loop once?
举例说明:统一时,我有2个盒子,两个盒子都标记为“盒子”。当在盒子上玩游戏时,一个盒子在飞机上,另一个在空中。 这是引擎的控制台:
Material 1 (UnityEngine.Material)
UnityEngine.Debug:Log(Object)
colourChangeArray:OnCollisionEnter(Collision) (at Assets/colourChangeArray.cs:28)
将物料1更改为物料2、3、4至5,然后执行1-5个循环10-20次
下面是我正在使用的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class colourChangeArray : MonoBehaviour
{
public int trigger = 1;
public Material[] material;
Renderer rend;
// Use this for initialization
void Start()
{
rend = GetComponent <Renderer> ();
rend.enabled = true;
rend.sharedMaterial = material[0];
}
// Update is called on collision
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "box")
{
for(int i = 0; i <material.Length; i++){
rend.sharedMaterial = material[i];
Debug.Log(rend.sharedMaterial);
}
}
else
{
rend.sharedMaterial = material[0];
Debug.Log(rend.sharedMaterial);
}
}
}
由于对象内部的一致性,材料之间的循环发生了几次。 您可以以某种方式减少它(我不记得了),但是我曾经有过类似的案例,无论您减少多少它都会发生。 因此,最好的方法是存储一个值,以表明它已经像以前这样完成:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class colourChangeArray : MonoBehaviour
{
public int trigger = 1;
public Material[] material;
Renderer rend;
private bool changeMaterialDone;
// Use this for initialization
void Start()
{
rend = GetComponent <Renderer> ();
rend.enabled = true;
rend.sharedMaterial = material[0];
changeMaterialDone = false;
}
// Update is called on collision
void OnCollisionEnter(Collision col)
{
if (!changeMaterialDone && col.gameObject.tag == "box")
{
changeMaterialDone = true;
for(int i = 0; i <material.Length; i++)
{
rend.sharedMaterial = material[i];
Debug.Log(rend.sharedMaterial);
}
}
else
{
rend.sharedMaterial = material[0];
Debug.Log(rend.sharedMaterial);
}
}
}
希望对您有所帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.