I came across this question on stackoverflow https://stackoverflow.com/questions/17147553/int-num-new-int-what-happens-when-this-line-executes . Wonder if there is any difference for sprite and spriteRender in unity between both of these commands sprite y=new sprite()
and sprite y;
or SpriteRenderer x=new SpriteRenderer()
and SpriteRenderer x;
? I tested in unity, both commands also generate the same option to attach game object, so do both have the same meaning as well?
\$\begingroup\$
\$\endgroup\$
1
\$\begingroup\$
\$\endgroup\$
In Unity components can't be created with new
, so such command as SpriteRenderer x = new SpriteRenderer();
must be avoided. In this particular case you will get x
initialzied with null
.
And input box for attaching gameObject is generated for every public
component in class.
Sprite
andSpriteRenderer
are reference types. That means thatSprite y;
orSpriteRenderer x;
initialize the value ofy
andx
respectively tonull
.Sprite y = new Sprite();
is not valid, becauseSprite
does not have a public constructor - you can create them via the static factory methodSprite.Create(...)
though. Since this is standard C# syntax, it's not game-development specific, and you can find Q&A about it on StackOverflow instead. \$\endgroup\$ – DMGregory♦ Jan 18 at 17:49