Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

Question How can I select any gameobject/s and not only the mono script is attached to ?

Discussion in 'Scripting' started by Chocolade, Jun 15, 2020.

  1. Chocolade

    Chocolade

    Joined:
    Jun 19, 2013
    Posts:
    947
    I created a mono script that is attached to a cube gameobject in the hierarchy :

    Code (csharp):
    1.  
    2. using System.Collections; using System.Collections.Generic;
    3.  
    4. using UnityEditor;
    5. using UnityEngine;
    6.  
    7. public class TestMono : MonoBehaviour
    8. {
    9.    public GameObject SelectedObject()
    10.    {
    11.        return Selection.activeGameObject;
    12.    }
    13. }
    14.  
    Then created editor script inspector with a button :

    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEditor;
    5. using UnityEditor.Experimental.TerrainAPI;
    6. using UnityEngine;
    7.  
    8. [CustomEditor(typeof(TestMono))]
    9. public class Test : Editor
    10. {
    11.    public override void OnInspectorGUI()
    12.    {
    13.        TestMono myTarget = (TestMono)target;
    14.  
    15.        if(GUILayout.Button("Test"))
    16.        {
    17.            myTarget.SelectedObject();
    18.        }
    19.    }
    20. }
    21.  
    The problem is that it's working only when selecting the cube where the mono script is attached to. But I want that if I select any gameobject in the hierarchy to get it in the script not only the gameobject it's attach to.
     
    Last edited: Jun 15, 2020
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Not quite sure what is it you are after. Are you saying you want to add a button to all scripts on a game object in the inspector?

    If so, what it is you are trying to achieve here and what is it you want the button to do?