I’ve been going through the Unity scripting tutorials and I have this question (and my relevant code is at the bottom): Why does the global Vector3 not require the “new” keyword, but the two local Vector3-s do?
using UnityEngine;
using System.Collections;
public class UnityLerp : MonoBehaviour {
Vector3 newPosition;
void Awake (){
newPosition = transform.position;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
ChangePosition();
}
public void ChangePosition (){
Vector3 positionA = new Vector3 (0,0,0);
Vector3 positionB = new Vector3(10,0,10);
if (Input.GetKeyDown (KeyCode.UpArrow)){
newPosition = positionA;
}
if (Input.GetKeyDown (KeyCode.DownArrow)){
newPosition = positionB;
}
transform.position = Vector3.Lerp (transform.position, newPosition, 3.0f * Time.deltaTime);
}
}
The first line you mention is just a declaration, and this vector is initialized in Awake using already existing Vector3 instance (transform.position).
On the other hand both vectors in ChangePosition method are declared and initialized on the same line. To initialize these variables, new Vector3 instances are created using constructors. And new keyword is required for constructor in C# (in JS it can be omitted).
A variable declared within the class scope can be accessed and initialized by other functions.
In contrast for local variable, it can only be initialized within the function which declare it.
class MyClass
{
int globalVar;
private void Function1()
{
int localVarA;
int localVarB = localVarA; // "localVarA" can only be initialized in this function
int localVarC = globalVar; // "globalVar" can be initialized by other functions
}
private void Function2()
{
globalVar = 100;
}
}