What does "as" mean???

What does “as” mean???

Examples:

Instantiate(prefab, new Vector3(i * 2.0F, 0, 0), Quaternion.identity) as Transform;

clone = Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;

Does it mean the same as???

greetings

http://www.dotnetperls.com/cast

it casts an object to a type that it may not currently be typed as.

For instance, Instantiate returns as the the value as type ‘object’. Which really could be ANYTHING. ‘as’ will try to cast it to Transform, if the object is a Transform the variable will contain the object with that type. Otherwise a null is returned.

It’s a “soft” cast.

Hard cast are as follow;

MyType variable = (MyType)value;

If for some reason “value” cannot be cast into “MyType”, the application will throw an exception and most likely crash.

In a soft cast;

MyType variable = value as MyType;

If value cannot be cast into MyType, the cast will return null and no exception is throw.

You can imagine “as” as being;

public T Cast<T>(object value)
{
    try
    {
        return (T)value;
    }
    catch (Exception)
    {
        return null;
    }
}
1 Like

Instantiate returns a UnityEngine.Object, and it can’t be anything. Seems like you’re mixing object and Object.

The important thing is that it Unity doesn’t know that it’s a Transform.

Nope, not mixing anything up. Just making generalized statements.

Also, for your sentence to make sense, it’d have to be:

“Seems like you’re mixing up object and UnityEngine.Object”

Seeing as ‘object’ is an alias for System.Object. So saying ‘Object’ on its own is ambiguous between the two.

If you want to get pedantic that is.