New keyword

Hello, i really need to ask this because i still dont quite understand the NEW keyword, how do i now when i need to use the NEW keyword? I know for the vector2 and vector3 how we use it or for new color. But i dont understand why do we use it for the NODE and for the QUEUE.
Can someone please explait it?

4 Likes

Hi PhantomGR,

If we write pure C# code, we would use the new keyword whenever we create a new C# object. We use it with a special method named constructor.

Here are a few examples:

Vector3 position = new Vector3(1f, 2f, 3f);
Player player = new Player("Rick");
Player player = new Player("Gary");
Enemy timmy = new Enemy();
List<int> numbers = new List<int>();
string[] names = new string[3];
Test test = new Test();

Is the syntax clear so far?

Then on to the problem: Unity. Unity is very complex, and it does not want us to create “Unity objects” ourselves. If our Enemy class inherits from MonoBehaviour and if we tried to call the constructor (new Enemy();), we would get a warning.

That’s why we do not use the new keyword all over the place when writing code for Unity. For non-Unity things like Queue, List, Node, etc., we call the constructor to create a new object.

Did this clear it up for you? :slight_smile:


See also:

6 Likes

Aaaa ok i got it, thank you
Have a nice day.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms