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

Cant Set Object Position

Discussion in 'Scripting' started by Daniel25097, Apr 20, 2016.

  1. Daniel25097

    Daniel25097

    Joined:
    Nov 10, 2015
    Posts:
    16
    Hi all,
    I want to make an object a child of other object and change it's position by scripting.
    This is my code:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class MiniMapCameraSetup : MonoBehaviour {
    5.  
    6.     public GameObject target;
    7.  
    8.     // Use this for initialization
    9.     void Start () {
    10.  
    11.         this.transform.parent = target.transform;
    12.  
    13.         //Reset Position
    14.         transform.position = new Vector3 (0, 60, 0);
    15.         transform.rotation = new Quaternion (90, 0, 0, 0);
    16.     }
    17. }
    The object does become a child but its position does'nt change.
    What is the proper way of doing that?

    Thanks.
     
  2. Nigey

    Nigey

    Joined:
    Sep 29, 2013
    Posts:
    1,129
    Code (CSharp):
    1. // The bool is called 'worldPositionStays'. Setting it to false changes the objects world position/scale/rotation relative to the parent.
    2. transform.SetParent(target.transform, false);
    One other thing, unless you really know what you're doing, it's generally best not to change Quaternion's by their raw numbers. If you're trying to go back to the initial rotation it's easily done with:

    Code (CSharp):
    1. transform.rotation = Quaternion.identity;
     
  3. Daniel25097

    Daniel25097

    Joined:
    Nov 10, 2015
    Posts:
    16
    Thank you for your quick reply Nigey.

    When i set the parent like you i'm getting the same result, I'ts the other 2 lines that does not work correctly.
    I want the object position and rotation will be at the exact values that i set them to, relative to the parent location (not 0,0,0 . Sorry if you misunderstood)

    So i'm asking again the same question, How can i change the x,y,z values of an object's position and rotation by scripting?
     
  4. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    Code (csharp):
    1.  
    2. transform.rotation=new Quaternion(90, 0, 0, 0);
    3.  
    NO

    quaternions are not in degrees. Do not try to build quaternions like this. Use the "Euler" functions to turn degrees into quaternions.
     
  5. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    you want transform.localPosition and transform.localRotation then
     
    Nigey likes this.
  6. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,376
    I wonder what the fourth angle would represent...