using UnityEngine; using System.Collections.Generi...

创建于:2025年8月7日

使用 O3 回答 Chat01

问题

using UnityEngine;
using System.Collections.Generic;

public class edificios : MonoBehaviour
{
public Dictionary<string, int[]> Edificios = new Dictionary<string, int[]>
{
{"alm0", new int[12]},
{"prod1", new int[12]},
{"prod2", new int[12]},
{"prod3", new int[12]},
{"prod4", new int[12]}
};

text
public void AñadirEdificio() { }

}


como puedo escribir la funcion para añadir un edificio al conteo?
para que entiendas, el string guarda el tipo de edificio, y los arrays los id de cada edificio individual dentro del tipo. Por ejemplo, un campo de trigo es igual a prod 1 (string) 0 (posicion dentro del array), y si el jugador construye un campo de trigo, la funcion debe añadir +1

思考

Considering the function to add a building

The user wants to create a function that increments the count of a specific building type based on a string-type key and uses arrays to track counts. Each building type has an array of size 12, initialized to zero, and when a building of a certain type is added, we need to either find the first available empty slot or increment the value at an existing index. The function might take parameters for the building type and the index ID to update the count. Let's figure out how to implement that.

Designing function to add buildings

The user wants a function to track building counts and add a new building by incrementing a value in the appropriate array. The array can either track counts or indicate free slots. If a building is added, the function could just increment the count or ideally find the first available slot (value == 0). I think using a loop to find the first available spot is the way to go here. I'll code that solution, providing the option to return the index of the new building or raise an error when the array is full.

Thought for 5 seconds

回答

Aquí tienes un ejemplo sencillo de cómo podrías implementar AñadirEdificio para que:

  1. Reciba el tipo de edificio que acaba de construir el jugador (p. ej. "prod1").
  2. Busque en el array asociado el primer hueco libre (valor == 0).
  3. Marque ese hueco con un 1 (o con otro código que uses: el id, la cantidad, etc.).
  4. Devuelva la posición que se ocupó, por si quieres usarla más tarde.
csharp
public intadirEdificio(string tipo) { // 1. ¿Existe ese tipo de edificio en el diccionario? if (!Edificios.TryGetValue(tipo, out int[] ids)) { Debug.LogError($"Tipo de edificio «{tipo}» no encontrado"); return -1; // -1 = error } // 2. Buscar la primera casilla libre (valor 0) for (int i = 0; i < ids.Length; i++) { if (ids[i] == 0) // hueco disponible { ids[i] = 1; // lo marcamos como ocupado return i; // devolvemos el id asignado } } // 3. Si llegamos aquí, el array está lleno Debug.LogWarning($"No hay espacio libre para «{tipo}»"); return -1; }

Cómo usarla

csharp
int idAsignado =adirEdificio("prod1"); if (idAsignado != -1) { // ¡Éxito! idAsignado es la posición dentro de "prod1" }

Cosas a tener en cuenta

  • Tamaño fijo vs. dinámico
    Con int[12] solo podrás construir 12 edificios de cada tipo.
    Si prefieres un límite dinámico, cambia a List<int>:

    csharp
    public Dictionary<string, List<int>> Edificios = new() { { "alm0", new List<int>() }, { "prod1", new List<int>() }, ... };

    y en lugar de buscar hueco libre, añadirías un elemento al final (Add(1)).

  • Almacenar más información
    Si necesitas guardar algo más que “presencia/ausencia” (p. ej. puntos de vida, nivel, instancia GameObject), sustituye el int por una estructura o clase propia.

Con estos cambios tu función ya incrementará correctamente el conteo (y te devolverá el id) cada vez que el jugador construya un nuevo edificio. ¡Suerte!

分享这个问答