Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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

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

  1. mandaxyz

    mandaxyz

    Joined:
    Apr 26, 2018
    Posts:
    6
    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(_gameObject.name);
    27.     }
    28. }
     
    Last edited: Apr 27, 2018
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,292
    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

    mandaxyz

    Joined:
    Apr 26, 2018
    Posts:
    6
    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