2017-07-28 112 views
-2

我無法讓我的循環工作。我可以讓它工作一次,或者沒有限制。我試圖讓硬幣實例化3次。我不認爲for循環本身是錯誤的,但結構的某處是。循環處於Looted函數中。無法讓我的循環工作

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class corpseKicked : MonoBehaviour { 

private Rigidbody2D rb; 
private Animator anim; 
public GameObject coinPrefab; 
public Transform coinSpawn; 
private bool kicked = false; 
public float timer = 2f; 
public GameObject deathFlamePrefab; 
private bool flamer; 
private bool pay = false; 
private bool broke = false; 

void Start() 
{ 
    anim = GetComponent<Animator>(); 
    rb = GetComponent<Rigidbody2D>(); 
} 

// Update is called once per frame 
void Update() 
{ 
    Looted(); 
} 

public void OnTriggerEnter2D(Collider2D other) 
{ 
    if (!kicked && other.gameObject.tag == "kickIndicator") { 
     kicked = true; 
     transform.Translate (0.0f, .05f, 0.0f); 
    } 
} 

public void Looted() 
{ 
    if (!pay && kicked) { 

     pay = true; 
     Instantiate (coinPrefab, coinSpawn.position, coinSpawn.rotation); 
     kicked = false; 
     pay = false; 
     for (int i = 1; i <= 3; i++) 

      Debug.Log ("$$$$$$$$$"); 
    } 
} 
+3

i = 3;'應該是'i <= 3;'。它是「繼續,而這是真實的」,而不是「當這是真的時停止」。 – Blorgbeard

+0

哦對。我忘了把它放回去。我得到了一個點,我試圖隨機組合。謝謝 –

+0

請勿更改您的問題以顯示更正的源代碼。這使它毫無價值。 – abto

回答

0
public GameObject deathFlamePrefab; 
private bool flamer; 
private bool pay = false; 
private bool broke = false; 
private int kickedCount = 0; 

void Start() 
{ 
    anim = GetComponent<Animator>(); 
    rb = GetComponent<Rigidbody2D>(); 
} 

// Update is called once per frame 
void Update() 
{ 
    Looted(); 
} 

public void OnTriggerEnter2D(Collider2D other) 
{ 
    if (!kicked && other.gameObject.tag == "kickIndicator") { 
     kicked = true; 
     transform.Translate (0.0f, .05f, 0.0f); 
    } 
} 

public void Looted() 
{ 
    if (!pay && kicked) { 

     pay = true; 

     kicked = false; 

     if (kickedCount < 3) 
     { 
      Instantiate (coinPrefab, coinSpawn.position, coinSpawn.rotation); 
      kickedCount++; 
     } 
     pay = false; 
    } 
} 

上午不確定什麼pay沒有,但你可能需要一個特殊的原因把它放在if聲明中

+0

它仍然實例化超過3次。基本上,玩家踢一個屍體,一枚硬幣出來。在玩家踢了3次屍體後,我希望玩家不能再從身上收集硬幣。 –

+0

那麼每踢1個硬幣? – SDSMTKyzer

+1

這是正確的,我的好人。 –

1

試試這個:

public void Looted() 
{ 
    if (!pay && kicked) { 

     pay = true; 
     Instantiate (coinPrefab, coinSpawn.position, coinSpawn.rotation); 
     kicked = false; 
     pay = false; 
     for (int i = 1; i <= 3; i++) 
     {  
      Debug.Log ("$$$$$$$$$"); 
     } 
    } 
} 

看到for條件的差異。把它想象成「只要這個條件成立就做這個循環。」由於i從1開始並在語句i++結束時遞增,因此它將按照您的預期運行三次。

這是比較常見和慣用雖然說

for (int i = 0; i < 3, i++) 

,除非有需要計數從1開始的

+0

相關提示它仍然在做。每次付款都是真實的,它仍然在實例化硬幣。感謝您的信息,但 –