Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

What does "as" mean???

Discussion in 'Scripting' started by psyhova, May 12, 2014.

  1. psyhova

    psyhova

    Joined:
    Oct 3, 2013
    Posts:
    32
    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
     
  2. Deleted User

    Deleted User

    Guest

  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,377
    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.
     
  4. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,716
    It's a "soft" cast.

    Hard cast are as follow;
    Code (csharp):
    1.  
    2. MyType variable = (MyType)value;
    3.  
    If for some reason "value" cannot be cast into "MyType", the application will throw an exception and most likely crash.

    In a soft cast;

    Code (csharp):
    1.  
    2. MyType variable = value as MyType;
    3.  
    If value cannot be cast into MyType, the cast will return null and no exception is throw.

    You can imagine "as" as being;

    Code (csharp):
    1.  
    2. public T Cast<T>(object value)
    3. {
    4.     try
    5.     {
    6.         return (T)value;
    7.     }
    8.     catch (Exception)
    9.     {
    10.         return null;
    11.     }
    12. }
    13.  
     
    Jadiker likes this.
  5. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    Instantiate returns a UnityEngine.Object, and it can't be anything. Seems like you're mixing object and Object.
     
  6. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,738
    The important thing is that it Unity doesn't know that it's a Transform.
     
  7. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,377
    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.