Hi everyone,
I am creating a simple item drop system in my game. I have a method that generates a random number, then uses a switch statement to generate an item and pass it along to another script.
However, I have run into an issue - I don’t want all switches to return a value. I basically want there be a chance that an item will not drop, and therefore the method does not return anything.
How can I do this? Currently this is my code:
public class ItemDrops
{
int randomNumber;
[SerializeField] GameObject weapon1;
[SerializeField] GameObject weapon2;
[SerializeField] GameObject weapon3;
public GameObject ItemGenerated()
{
randomNumber = Random.Range(0, 12);
switch(randomNumber)
{
case 1:
return weapon1;
case 2:
return weapon2;
case 3:
return weapon3;
default:
break;
}
}
}
Obviously, since not all values return something, I have an error.
Hopefully this is just something simple or there is another way of doing this I am not familiar with
You could return a null, then have the locations that call this handle it. That’s pretty common practice.
However, if you have lots of call sites that might be painful.
Therefore you could return something useless, such as a blank prefab that is an empty gameObject. But then it might show up in your inventory.
Another thing you could do is have the notion of a “weapon_none” and return that. It could be an invisible gameobject or whatever.
Basically, all data is just 1s and 0s, and with engineering, we are making choices to make data mean something.
If you craft your data so that it maps to all the things you want to represent, it helps you reason about the issue.
1 Like
Thanks for the reply! Can you elaborate about how I would go about handling this? This method is actually only being called in one place, so this might actually be the best option.
I guess a start would be,
GameObject item = ItemGenerated();
if (item != null)
{
// do something with the generated GameObject (instantiate it or whatever)
// instantiate and replace the reference for ease
item = Instantiate<GameObject>( item);
// etc...
Debug.Log( "You got a " + go.name);
}
else
{
// otherwise don't!
Debug.Log( "You got swindled... the crate was empty!");
}
1 Like
Unfortunately the problem I am running into is that without all code paths returning a value, I get a compiler error in Unity. So I can’t actually apply this logic unless there is a workaround I am unaware of.
edit: I’m a dummy, I didn’t realize you can simply return null!
Yessir, this is the magic… for any nullable type you can return a null.
If you were returning an integer or a Vector3 or float or other value type, that would not be possible, as those are not nullable types. Hopefully that tidbit will save you head scratching in the future!
Just remember, if you return a null and other code that got it back tries to use it, it’s still just a full-on legitimate null reference error, so you have to be sure to test for it.!
1 Like
Thanks so much! It’s working perfectly now!
1 Like