Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question code dont work

Discussion in 'Scripting' started by Regivaldo, Aug 20, 2023.

  1. Regivaldo

    Regivaldo

    Joined:
    Apr 14, 2022
    Posts:
    1
    i want top create a code in that spawner enemies randomly, and after a determinated amount of enemies died i want that a speed of spawn increase a bit, so i writte a code and for some reason the speed os spawn dont increase e i dont know why, i would someone see what's problem. (sorry my ingles).




    public GameObject xpBall;
    public GameObject[] animalsPrefabs;
    public TextMeshProUGUI killsText;

    private float spawnRangeX = 8.5f;
    private float spawnRangeZ = 34.0f;
    private float startDelay = 2.0f;
    private float frequencySpawn = 1.5f;
    [SerializeField] private float currentSpeed = 0;
    private float increaseSpeed = 0.1f;
    private float maxSpeed = 0.5f;

    //contador de kills
    public int enemiesKilled = 0;
    private int spawnRatingXp = 0;
    public int espacoEntreXp = 5;

    void Start()
    {
    currentSpeed = frequencySpawn;
    spawnRatingXp = espacoEntreXp;
    //spawna inimigos aleatoriamente pelo mapa
    InvokeRepeating("RandoAnimalSpawn", startDelay, currentSpeed);
    }

    void Update()
    {
    killsText.text = ("Kills: ")+ enemiesKilled.ToString();

    }

    void RandoAnimalSpawn()
    {

    // animals will spawner over a scene
    int animalIndex = Random.Range(0, animalsPrefabs.Length);
    Vector3 spawnPos = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 0, spawnRangeZ);
    Instantiate(animalsPrefabs[animalIndex], spawnPos, animalsPrefabs[animalIndex].transform.rotation);
    if (enemiesKilled >= spawnRatingXp)
    {
    currentSpeed -= increaseSpeed;
    currentSpeed = Mathf.Max(currentSpeed, maxSpeed);
    }

    }
    public void EnemyKilledByProjectile()
    {
    enemiesKilled++;

    // Verificar se todos os inimigos foram mortos
    if (enemiesKilled >= spawnRatingXp)
    {
    Vector3 spawnPos = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 3, spawnRangeZ);
    Instantiate(xpBall, spawnPos, xpBall.transform.rotation);
    spawnRatingXp = spawnRatingXp + espacoEntreXp;
    // Execute qualquer lógica adicional aqui, como vitória do jogador ou mudança de cena.
    }

    }[/code]
     
  2. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    It's because
    InvokeRepeating()
    only works for as long as you declare it:
    https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html
    And your
    startDelay
    is only 2 seconds, so after 2 seconds have passed:
    void RandoAnimalSpawn()

    Is no longer being called, so it's part where it changes speed doesn't read anymore.

    Your better off not using an
    Invoke
    , and having
    if
    questions in your
    Update()
    to handle this.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.

    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, log output, variable values, and especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)

    The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven't put effort into finding the documentation, why should we bother putting effort into replying?

    Do not TALK about code without posting it. Do NOT retype code. Do NOT post screenshots of code. Use copy/paste and post code properly. ONLY post the relevant code, and then refer to it in your discussion. Do NOT post photographs of code.

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/
     
  4. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,082
    You've worded this in a very odd way. It reads as if you're suggesting that the method is only called once but that's not the case. You only have to call
    InvokeRepeating
    once to have it continually be called.

    You can't change the speed of an
    InvokeRepeating
    after it's been started. You need to cancel the invoke with
    CancelInvoke
    and then create a new one that matches the new speed. Or just use a coroutine like this.

    Code (csharp):
    1. using System.Collections;
    2. using UnityEngine;
    3. using TMPro;
    4.  
    5. public class EnemySpawner : MonoBehaviour
    6. {
    7.     public GameObject xpBall;
    8.     public GameObject[] animalsPrefabs;
    9.     public TextMeshProUGUI killsText;
    10.  
    11.     private float spawnRangeX = 8.5f;
    12.     private float spawnRangeZ = 34.0f;
    13.     private float startDelay = 2.0f;
    14.     private float frequencySpawn = 1.5f;
    15.     [SerializeField] private float currentSpeed = 0;
    16.     private float increaseSpeed = 0.1f;
    17.     private float maxSpeed = 0.5f;
    18.  
    19.     public int enemiesKilled = 0;
    20.     private int spawnRatingXp = 0;
    21.     public int espacoEntreXp = 5;
    22.  
    23.     void Start()
    24.     {
    25.         currentSpeed = frequencySpawn;
    26.         spawnRatingXp = espacoEntreXp;
    27.         StartCoroutine(AnimalSpawnRoutine());
    28.     }
    29.  
    30.     void Update()
    31.     {
    32.         killsText.text = "Kills: " + enemiesKilled.ToString();
    33.     }
    34.  
    35.     IEnumerator AnimalSpawnRoutine()
    36.     {
    37.         yield return new WaitForSeconds(startDelay);
    38.         while (true)
    39.         {
    40.             RandoAnimalSpawn();
    41.             yield return new WaitForSeconds(currentSpeed);
    42.         }
    43.     }
    44.  
    45.     void RandoAnimalSpawn()
    46.     {
    47.         int animalIndex = Random.Range(0, animalsPrefabs.Length);
    48.         Vector3 spawnPos = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 0, spawnRangeZ);
    49.         Instantiate(animalsPrefabs[animalIndex], spawnPos, animalsPrefabs[animalIndex].transform.rotation);
    50.         if (enemiesKilled >= spawnRatingXp)
    51.         {
    52.             currentSpeed -= increaseSpeed;
    53.             currentSpeed = Mathf.Max(currentSpeed, maxSpeed);
    54.         }
    55.     }
    56.  
    57.     public void EnemyKilledByProjectile()
    58.     {
    59.         enemiesKilled++;
    60.  
    61.         if (enemiesKilled >= spawnRatingXp)
    62.         {
    63.             Vector3 spawnPos = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 3, spawnRangeZ);
    64.             Instantiate(xpBall, spawnPos, xpBall.transform.rotation);
    65.             spawnRatingXp += espacoEntreXp;
    66.         }
    67.     }
    68. }
     
    Last edited: Aug 20, 2023
    wideeyenow_unity likes this.
  5. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    No, lol, you're right, I for some odd reason was thinking it was just Invoke for how many seconds. Totally did not pay attention to the word
    Repeating
    . :oops: