1
\$\begingroup\$

Is it possible to change localScale.x in Unity without creating a new Vector3?

\$\endgroup\$
2
  • \$\begingroup\$ What's the problem with transform.localScale = new Vector3(changedXScale, transform.localScale.y, transform.localScale.z); that you're trying to solve? This can be expressed in several different ways, depending on your objective. \$\endgroup\$
    – DMGregory
    Sep 22, 2017 at 16:30
  • \$\begingroup\$ @DMGregory, I was worried about the performance and the answer tackled the issue. Thank you for the attention. \$\endgroup\$
    – qqqqqqq
    Sep 22, 2017 at 20:32

1 Answer 1

2
\$\begingroup\$

Yes, simply write: localScale.x = 100.0 or whatever you'd like.

This doesn't work when the localScale you're referring to (which is not clear) is a property of some instance, because C# properties are just syntactic sugar for function invocations and you'd thus be changing a member of a local temporary, not the actual backing Vector3. In those cases you must replace the entire Vector3, as in foo.localScale = new Vector3(x, y, z);.

This may be a minor inconvenience in terms of typing, but since Vector3 is a value type there is no appreciable performance overhead (you're not creating garbage on the heap, for example, as you would if Vector3 was a reference type).

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .