Search Unity

When should you use NEW?

Discussion in 'Scripting' started by evan140, May 14, 2015.

  1. evan140

    evan140

    Joined:
    Jul 15, 2014
    Posts:
    72
    I don't understand when, in Unity, it is appropriate to use "new" For example, if I fire a rocket, I instantiate a prefab of a rocket. If I want to have a "frog" I would drop a "frog.cs" script onto a gameobject.

    When is it appropriate in Unity to use the new keyword?

    (from - http://unity3d.com/learn/tutorials/modules/beginner/scripting/data-types )
    Code (CSharp):
    1. public class DatatypeScript : MonoBehaviour
    2. {
    3.     void Start ()
    4.     {
    5.         //Value type variable
    6.         Vector3 pos = transform.position;
    7.         pos = new Vector3(0, 2, 0);
    8.    
    9.         //Reference type variable
    10.         Transform tran = transform;
    11.         tran.position = new Vector3(0, 2, 0);
    12.     }
    13. }
    (from - https://unity3d.com/learn/tutorials/modules/beginner/scripting/classes )

    Code (CSharp):
    1.   public Stuff myStuff = new Stuff(50, 5, 5);
    2.    
    3.     public Stuff myOtherStuff = new Stuff(50, 1.5f);
    4.    
     
  2. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    When you are creating a new object for the most part. Ideally, for beginners, anytime in C# that you encounter a situation to use Vector3, you have to use the new keyword.

    Setting position, rotation, and scale require a "new" vector3.

    If you want to create an object , you have to do so using a constructor through the "new" keyword
     
  3. Fajlworks

    Fajlworks

    Joined:
    Sep 8, 2014
    Posts:
    344
    In Unity, for the most part you use "new" when you want to instantiate an object or create a struct that doesn't derive from MonoBehaviour.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,737
    Adding to what Fajlworks said above, the way to create a new Monobehavior-derived class is to use the .AddComponent<T>() method on a GameObject, which does the necessary behind-the-scenes plumbing to integrate the new Monobehavior with the given game object.