Hello I’m a beginner in game dev and I’m trying to make a simple shopping game where players can only add 10 items to their basket but I don’t know how to add a limit to the capacity in my basket in case players already have 10 items in their basket. I made a debug log on my code to check if it was working well.
public class Basket : MonoBehaviour
{
private GameObject[] itemList;
public int number = 11;
private bool isFull = false;
void Start()
{
itemList = GameObject.FindGameObjectsWithTag("item");
}
private void Update()
{
if (itemList[number])
{
isFull = true;
Debug.Log("item limit reached");
}
}
}
But instead, what I got was the debug log repeating infinitely like this.
I don’t know what I’m doing wrong. Any help would be appreciated.
if you want it to only show once then add not isFull to the statement, basically you are saying every update if we have reached max set isFull to true. then it checks if its at max again and sets it to true again. it needs to know that you only want to set isFull to true if its not already true.
if (itemList[number] && !isFull)
I guess you have to change quite some things in here.
Let us address the “fullness”-check first.
The line
if (itemList[number])
takes the element at index number
and checks if it is unequal null. Why? Because your current code does the same thing as this here:
GameObject go = itemList[number];
if(go != null)
//do something
What you instead want to do is the following:
if(itemList.Length > number)
//help, basket is full
The problem you generally have is that this still will always trigger.
Because you have all your items in your scene already. In your Start
function you search for all these items and add them to the itemList
. So whenever you start the game your current script will make it so that all Baskets already always contain all items which there are.