Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I properly create invalid Vector3 in Unity?

I often need to pass invalid location to functions that optionally can use location (eg. RTS unit action). But this does not compile:

public abstract void CastSpell(Spell spell, Vector3 targetLocation = null);

So how can I make a proper invaid Vector3 to determine invalid/"don't care" locations? I've seen things like vector with -999999 coordinates - but that's a nasty trick that might cause bugs (eg. on huge maps).

like image 963
Tomáš Zato - Reinstate Monica Avatar asked Dec 03 '25 17:12

Tomáš Zato - Reinstate Monica


1 Answers

I had a similar problem in the past, I found there was two solutions. The first solution was to create a wrapper for the class.

Class Vector3Wrapper
{
    Vector3 vector;
}

Then I would simply set the Vector3Wrapper to null then if it wasnt null access its vector. A better method would be making it a Nullable type. A example is below.

http://unitypatterns.com/nullable-types/

public class Character : MonoBehaviour 
{
    //Notice the added "?"
    Vector3? targetPosition;
 
    void MoveTowardsTargetPosition()
    {
        //First, check if the variable has been assigned a value
        if (targetPosition.HasValue)
        {
            //move towards targetPosition.Value
        }
        else
        {
            //targetPosition.Value is invalid! Don't use it!
        }
    }
like image 70
marsh Avatar answered Dec 06 '25 10:12

marsh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!