[英]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?
To give some context: In unity I have 2 boxes, which are both tagged "box" One box is on a plane and the other in the air, when the game is played on box falls on the other. 举例说明:统一时,我有2个盒子,两个盒子都标记为“盒子”。当在盒子上玩游戏时,一个盒子在飞机上,另一个在空中。 Here is the console for the engine:
这是引擎的控制台:
Material 1 (UnityEngine.Material)
UnityEngine.Debug:Log(Object)
colourChangeArray:OnCollisionEnter(Collision) (at Assets/colourChangeArray.cs:28)
With material 1 changing to material 2, 3, 4 to 5 and then doing the 1-5 cycle 10-20 times 将物料1更改为物料2、3、4至5,然后执行1-5个循环10-20次
Below is the code i'm using 下面是我正在使用的代码
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);
}
}
}
The cycle between materials happen a few times because of the internal bounciness of the objects in unity. 由于对象内部的一致性,材料之间的循环发生了几次。 You can decrease it somehow (which I don't remember) but, I had a similar case once and no matter how much you decrease that it happens.
您可以以某种方式减少它(我不记得了),但是我曾经有过类似的案例,无论您减少多少它都会发生。 So the best approach would be to store a value indicating it has been done before like this:
因此,最好的方法是存储一个值,以表明它已经像以前这样完成:
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);
}
}
}
I hope it helps you :) 希望对您有所帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.