Search Unity

  1. We would like to hear your feedback about Unity and our products. Click here for more information.
    Dismiss Notice

[SOLVED] Find a game object and how to move it?

Discussion in 'Scripting' started by mandaxyz, Apr 27, 2018.

  1. mandaxyz


    Apr 26, 2018
    Hi, my questions are in the title and in the code below.
    Code (CSharp):
    1. // Hierarchy:
    2. //   Main Camera
    3. //   Directional Light
    4. //   GameObject
    5. //      Cube
    6. //   GameObject (1)  <--  I duplicated the GameObject above, then I have children with same name.
    7. //      Cube
    8. //   ScriptGameObject  <--  The script is in this game object, because I want to make the
    9. //                          script global.
    10. //                          Do you know another idea where I should put my script to make it global?
    11. //   ...
    12. public class Example : MonoBehaviour
    13. {
    14.     GameObject _gameObject;
    15.     void Start()
    16.     {
    17.         _gameObject = GameObject.Find("Cube");
    18.         // There are 2 game objects named "Cube" in the scene.
    19.         // Which of the 2 game objects Cube and Cube will be found by Find()?
    20.         // Why there is no warning in Unity when there are game objects with the same name?
    21.     }
    22.     void Update()
    23.     {
    24.         // I want to move a game object but I cannot. How to do it?
    25.         _gameObject.transform.position.Set(0.0f, 10.0f, 0.0f);
    26.         Debug.Log(;
    27.     }
    28. }
    Last edited: Apr 27, 2018
  2. Baste


    Jan 24, 2013
    GameObject.Find should be avoided in almost all instances. It's main problem is what you've discovered - there's no way to distinguish between two objects with the same name. It's also very, very slow, as it looks though all the objects in your scene.

    The standard way to do what you're doing is to set _gameObject public, and then assign it in the inspector.

    To set the position of an object, it's just:
    Code (csharp):
    1. _gameObject.transform.position = new Vector3(0.0f, 10.0f, 0.0f);
    I also recommend the basic tutorials, they go through a lot of this stuff! Check the learn section at the top of this page.
    mandaxyz likes this.
  3. mandaxyz


    Apr 26, 2018
    Thank you very much.
    I set _gameObject public and then assign it in the inspector, then it works, great!
    I will try to learn the tutorials that you said.
    Last edited: Apr 27, 2018