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

Find an object by a part of its name

Discussion in 'Scripting' started by anme2018, Sep 26, 2019.

  1. anme2018

    anme2018

    Joined:
    Apr 10, 2016
    Posts:
    13
    Hi,

    I have many objects with different names

    buidling01
    buidling02
    buidling01_window02
    buidling01_window01
    buidling02_window01
    and so on....

    To find an object with full name, i have this simple script:


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4.  
    5.  
    6. public class ExampleClass : MonoBehaviour
    7. {
    8.     public GameObject myObjectName;
    9.  
    10.     void Example()
    11.     {
    12.      
    13.         myObjectName = GameObject.Find("buidling01_window02");
    14.  
    15.    
    16.     }
    17. }
    But how do I change the script to find only a part of the name, for example "window01" oder "buidling02"?
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Why do you need to find the objects? I would think of a different approach as find with string is slow. You could have a class which stores a reference to the building parts.
     
  3. anme2018

    anme2018

    Joined:
    Apr 10, 2016
    Posts:
    13
    ok... how could that actually work?
     
  4. stefan_s_from_h

    stefan_s_from_h

    Joined:
    Nov 26, 2017
    Posts:
    72
    Take a look at the first example for Transform: You can iterate over all children of this game object. So just put all game objects under a parent one and iterate once(!) over them and remember all necessary information for your task.
     
  5. Emolk

    Emolk

    Joined:
    Feb 11, 2014
    Posts:
    241
    If all your building objects are tagged the same, you could have two fields in each object called name1 and name2 and set the name1 and name2 fields as the same as the first and second parts of their name. Then do something like this:

    Code (CSharp):
    1. gameObjects = GameObject.FindGameObjectsWithTag("Building");
    Then iterate through gameObjects and check for your search criteria in both name1 and name2 fields.
     
  6. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    Before you go down that partial route, what are you ging to do with the OTHER objects that match the partial Name, or is that the Goal, to find all objects whose name have the same substring?
     
  7. anme2018

    anme2018

    Joined:
    Apr 10, 2016
    Posts:
    13
    My goal is: I want to make them visible or invisible in different combinations.