0
\$\begingroup\$

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?

\$\endgroup\$
1
  • \$\begingroup\$ Following the standard rules for c#, Sprite and SpriteRenderer are reference types. That means that Sprite y; or SpriteRenderer x; initialize the value of y and x respectively to null. Sprite y = new Sprite(); is not valid, because Sprite does not have a public constructor - you can create them via the static factory method Sprite.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
0
\$\begingroup\$

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.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.