two places in the getbylevel method we return default. What is default and what is returned here?
also inside the for loop in GetRandomDrops we call GetRandomNumberOfDrops. This must be called only once right for the entire life of the for loop?
default
is a built in C# thing. It is the default value of whatever type it refers to - if it’s an int
it will be 0. if it’s any object, it will be null. Value types cannot be null, so it will just be an uninitialised instance. Like the default for Vector3
is the same as Vector3(0, 0, 0)
In GetByLevel
it will be the default value for whatever T
is. Unfortunately I haven’t touched the RPG course in a long time, so I cannot remember what we use this for, now.
Hey, in GetByLevel we give the method an array of numbers of either floats or ints, and we choose which number in the array we give back based on the enemy level.
static T GetByLevel<T>(T[] values, int level)
{
// If we have no lenght in the array, no values, we give a default value.
if(values.Length == 0)
{
return default;
}
// If level is greater than lenght of array we return last element in the array.
if(level > values.Length)
{
return values[values.Length - 1];
}
// If level is less than or equal to 0 we give a default value.
if (level <= 0)
{
return default;
}
// Return value thats for the level we enter.
return values[level - 1];
Cool, so it will be either the default for an int (0) or the default for a float (0f) depending on which we gave it. In older versions of C# you had to specify the type; default(int)
but now the compiler can infer it. For this, it would’ve been default(T)
thnx!
Yes, this is an error in the code. We should call GetRandomNumberOfDrops and cache the result to use within the for() clause.
I missed that part of the question. My bad. Impulsive again. Just jumped right in with the ‘default’ answer and didn’t finish reading the question.
This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.