- Home /
C# Question Regarding"new" keyword and Vector3 type
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);
}
}
Answer by ArkaneX · Dec 19, 2013 at 10:14 AM
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).
The easiest way to know when the new keyword should be used is to consider this: "Am I making a new one of the object?" Notice that each time you use the new keyword, you define a vector that's not used anywhere else - it's new. The times when you don't are grabbing the vector from somewhere else - it's an old vector, so you don't need the new keyword. It's quite simple really, and it does exactly what it says: makes a new one.
Thank you everyone for your responses, and indeed, I just have to keep in $$anonymous$$d that I don't have to create everything from scratch.
Answer by Yword · Dec 19, 2013 at 11:17 AM
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;
}
}
That's true, but poorly explained and not actually an answer to the question being asked.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Roguelike Tutorial Expansion of Layout 1 Answer
CS1502 and CS1503 Error 0 Answers
Slow WorldToScreenPoint () 0 Answers