简体   繁体   中英

What are the alternatives to using “FindObjectsOfType”?

As of right now I am using Unity with C#. My Code are as follows:

    var buttons = FindObjectsOfType<DefenderButton>();

    foreach (DefenderButton button in buttons) // color unselect resets back color
    {
        button.GetComponent<SpriteRenderer>().color = new Color32(41, 41, 41, 255); 
    }

What are the alternatives to using FindObjectsOfType ?

Set the same tag for all GameObjects that contain the class DefenderButton in Unity or use the property tag in GameObject class to set the tag. For this answer i will use tag any . After you set the tag you can do the following:

foreach (GameObject obj in GameObject.FindGameObjectsWithTag("any"))
{
    foreach (DefenderButton button in obj.GetComponents<DefenderButton>())
    {
       button.GetComponent<SpriteRenderer>().color = new Color32(41, 41, 41, 255); 
    }
}

Find object with a string property GameObject.Find() https://docs.unity3d.com/ScriptReference/GameObject.Find.html

Finds objects you marked with a certain tag GameObject.FindWithTag() https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html

And lastly (that i know of) you can just traverse the GameObject hierarchy and 'Find' stuff, like for example (pseudo-code just to give you an idea):

Lets say your gameobjects are arranged like so:

- obj 0
  - Obj1
    - obj1A
    - obj2B
  - Obj2

If you're in Obj2 , you can do the following:

var obj2B = transform.parent // obj0
              .Children.First() // obj1
                 .Children.Last() // obj2B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM