【问题标题】:c# Spawn Interval Changerc# 生成间隔更改器
【发布时间】:2022-11-25 15:49:14
【问题描述】:

我在下面添加我的代码。我的错是什么,有人可以帮助我吗? 我想当 SpawnRandomBall 函数运行两次时,spawnInternal 变成 spawnInternal2。所以我创建了一个新变量,称为“check”。该变量在 SpawnRandomBall 函数运行时增加。我将变量设置为公共变量。通过这种方式,我可以看到“检查”变量增加或不增加。 “检查”变量正在毫无问题地增加。当veriable值等于3时,必须是'else if'运行。但不幸的是它不起作用。

我想问题是我在 Start() 函数中运行我的代码。但我不知道我该怎么做才好。

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

public class SpawnManagerX : MonoBehaviour
{
    public GameObject[] ballPrefabs;

    private float spawnLimitXLeft = 14.5f;
    private float spawnLimitXRight = 24;
    private float spawnPosY = 10;

    private float startDelay = 1.0f;
    private float spawnInterval = 4.0f;
    private float spawnInterval2 = 2.0f;
    public int check;

    // Start is called before the first frame update
    void Start()
    {
        if (check <= 2)
        {
            InvokeRepeating("SpawnRandomBall", startDelay, spawnInterval);
        }
        else if (check > 2)
        {
            InvokeRepeating("SpawnRandomBall", startDelay, spawnInterval2);
        }
    }
    // Spawn random ball at random x position at top of play area
    void SpawnRandomBall ()
    {
        // Generate random ball index and random spawn position
        Vector3 spawnPos = new Vector3(-21, spawnPosY, Random.Range(spawnLimitXLeft, spawnLimitXRight));
        int ballIndex = Random.Range(0, 3);

        // instantiate ball at random spawn location
        Instantiate(ballPrefabs[ballIndex], spawnPos, ballPrefabs[ballIndex].transform.rotation);
        check += 1;
    }

}

我想将 SpawnInternal 变量更改为 SpawnInternal2

【问题讨论】:

  • Start 方法是如何被调用的?
  • 其实我是初学者。如果你能为我解释,我将不胜感激

标签: c# unity3d


【解决方案1】:

如果 Start 被调用一次,那么 else if 永远不会运行。代码不只是在else if 等待check 更新。

您只需要管理在 SpawnRandomBall 方法中运行的代码。

你将需要尝试这样的事情:

// Start is called before the first frame update
void Start()
{
    InvokeRepeating("SpawnRandomBall", startDelay, spawnInterval2);
}
// Spawn random ball at random x position at top of play area
void SpawnRandomBall()
{
    check++;
    if (check == 1 || check == 3)
        return;
        
    // Generate random ball index and random spawn position
    Vector3 spawnPos = new Vector3(-21, spawnPosY, Random.Range(spawnLimitXLeft, spawnLimitXRight));
    int ballIndex = Random.Range(0, 3);

    // instantiate ball at random spawn location
    Instantiate(ballPrefabs[ballIndex], spawnPos, ballPrefabs[ballIndex].transform.rotation);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 2022-12-04
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多