簡體   English   中英

我在C#中有一個for循環,可與Unity引擎配合使用。 但是我該怎么做,使其只調用一次循環?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM