Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Assigning all Transform Properties at Once

Discussion in 'Scripting' started by UnityGuy1988, Aug 9, 2023.

  1. UnityGuy1988

    UnityGuy1988

    Joined:
    Jan 12, 2020
    Posts:
    24
    Is there a way to assign all the properties of a gameobject's transform (i.e. position, rotation, scale) to that of a second game object with one line of code? I've been typing it out like this:

    transform.position = otherObject.position;
    transform.eulerAngles= otherObject.eulerAngles;
    transform.scale = otherObject.scale;

    Surely there's a way to assign all values at once? I would also like to do the same thing for the UI Image "Rect Transform" component using the TMPro namespace. This contains a number of properties including position X, Y & Z, as well as width and height, plus anchor values including scale and rotation. In short, a lot of fields, so assigning them all at once would be a lot more convenient.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,558
    I don't think there is...

    Beware that this:

    may have very wonky things going on.

    Try instead:

    Code (csharp):
    1. transform.rotation = otherObject.rotation;
    Here's why:

    All about Euler angles and rotations, by StarManta:

    https://starmanta.gitbooks.io/unitytipsredux/content/second-question.html
     
    Bunny83 likes this.
  3. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    3,899
    Bunny83 and Kurt-Dekker like this.
  4. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,739
  5. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    521
    I assume (if it matters to you) you could write an extension method and it would be available to your Transform objects. https://learn.microsoft.com/en-us/d...g-guide/classes-and-structs/extension-methods
     
  6. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    9,900
    Having methods like
    SetPositionAndRotation
    isn't about aesthetics. It's a performance improvement since Unity won't refresh its scene graph twice with separate position and rotation calls. It does once after set the position and the rotation. These scene graph updates can add up if you do it in
    Update
    or something and you have many of them since they need to update the transform-graph (parent-child relationships between game objects).
    Making an extension method by you (or anyone else, really) is an aesthetic choice, since you would still call Unity's API separately. Which can be done, just we should recognize, it is not the same thing.
     
    tleylan and spiney199 like this.