1
\$\begingroup\$

I have a game object(object) with a script component(myscript) attached.

I have a reference to myscript component through getComponent, and I want to change the transform of the gameObject the script is attached to.

myscript.gameObject.transform = (new value);

The above code gives me error,

Property 'UnityEngine.GameObject.transform' is read only.

Is there a way to get a read-write version?

\$\endgroup\$
2
  • \$\begingroup\$ hmm.. it seems that I can just use myscript.transform but it also gives the same read-only error. \$\endgroup\$
    – onguarde
    Commented Nov 6, 2012 at 9:42
  • \$\begingroup\$ What value do you want to change? Position? Try assigning to transform.position. Local rotation? Try assigning to transform.localRotation. \$\endgroup\$
    – Eric
    Commented Nov 6, 2012 at 9:49

2 Answers 2

2
\$\begingroup\$

Transform is read-only C# property. I guess it could be defined pretty most this way:

public Transform transform{get;}

So, you can't assign directly a Transform to another Transform (you don't have set accessor defined). You are forced to assign individual fields of each Transform to the other.

For example:

myscript.gameObject.transform.rotation = otherScript.gameObject.transform.rotation;
myscript.gameObject.transform.position = otherScript.gameObject.transform.position;
...
\$\endgroup\$
1
  • \$\begingroup\$ FIY, it doesn't have a setter defined at all, and getter reads the value from native code. \$\endgroup\$
    – Nevermind
    Commented Nov 6, 2012 at 13:08
1
\$\begingroup\$

If by "change the transform" you mean "change position/rotation/scale" of my object, you have to change these individually:

gameObject.transform.position = ...;
gameObject.transform.rotation = ...;
gameObject.transform.localScale = ...; // note that you CAN'T change global scale, as it's not actually a vector

If by "change the transform" you mean "change my object's parent", you have to change parent propery:

gameObject.transform.parent = someOtherTransform;
\$\endgroup\$

You must log in to answer this question.

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