Search Unity

Changing Vector3 components in C#

Discussion in 'Scripting' started by nafonso, Mar 26, 2007.

  1. nafonso

    nafonso

    Joined:
    Aug 10, 2006
    Posts:
    377
    Hi,

    I'm doing a couple of scripts in C# and I found something which looks kind of odd to me. I tried the following code:
    Code (csharp):
    1. mainTextBackground.transform.localScale.y = 0.1f*numberOfLines;
    In C# it says that this is not possible... No problem, looked at the docs and there was an index access (i.e. [index]).

    So I tried the following code:
    Code (csharp):
    1. mainTextBackground.transform.localScale[1] = 0.1f*numberOfLines;
    But with the Debug.Log, I saw that the value isn't updating. If this isn't possible it should at least give me an compile error (maybe outdated mcs?).

    I could only change a Vector3 with the following code:
    Code (csharp):
    1. mainTextBackground.transform.localScale = new Vector3( 1, 0.1f*numberOfLines, 1);
    Is this expected behaviour?

    Regards,
    Afonso
     
  2. Willem

    Willem

    Joined:
    Mar 9, 2007
    Posts:
    184
    That's what I ended up having to do as well. C# doesn't see the Vector3 as writable in any other way AFAICT.
     
  3. freyr

    freyr

    Joined:
    Apr 7, 2005
    Posts:
    1,148
    This is because localScale is a property (and not a field) returning a value type. C# does not allow modifying struct members through a property. (Since structs are always passed by value, and therefore the property returns a copy of the vector.)

    To work around this limitation, you have to read the value, modify it and assign it back:
    Code (csharp):
    1. Vector3 scale = mainTextBackground.transform.localScale;
    2. scale.y =0.1f*numberOfLines;
    3. mainTextBackground.transform.localScale=scale;