#Use of unassigned variable

1 messages · Page 1 of 1 (latest)

viral kettle
#

As the name implies, I simply want to find the nearest GameObject

misty coral
#

Because it might be unassigned shrug

viral kettle
#

Uh

#

But Im assigning it

misty coral
#

You're not

viral kettle
#

Setting it to null initially works but why it wont work without it

misty coral
#

What if no boats are within Distance

viral kettle
#

So ur saying there are chances it might be null?

#

Gotcha

#

Thx!

misty coral
#

The error was because there was a possible route the code could take where no objects are within Distance, and so it would be "unassigned" because NearestBoat was never set to any object

#

You need to consider every possible path the code can take

viral kettle
#

Aight

viral kettle
#

I mean I could set it to the distance from the first boat but this is a nice shorcut

misty coral
#

Absolutely, float.PositiveInfinity or float.MaxValue are both fine. You want it to be initialised to a high value so that all objects are potentially considered

But don't use Mathf.Infinity

viral kettle
#

Why?

misty coral
#

Mathf.Infinity is an absolutely pointless value that Unity wrote for.. literally no reason.
It is identical to float.PositiveInfinity - that's how it's defined to be. The difference is, float.PositiveInfinity is standard C#/.NET, and will work everywhere. Mathf.Infinity is strictly a Unity thing

#

so it's good habit to use float.PositiveInfinity, because you will know what that value is wherever you take your C# skills

viral kettle
#

Aight

#

Thanks!