我无法让我的for循环工作。我可以让它工作一次,或没有限制。我试图让硬币最多实例化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 ("$$$$$$$$$");
}
}
答案 0 :(得分: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开始计算。
答案 1 :(得分: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
声明中