Unity gets the number of sub-objects, gets the parameters of other scripts, gets the script name, finds the displayed objects, shows and hides the objects

Get the number of child objects

I have such a level,
insert image description here
I want to get the number of levelSelectButtons in the levelSelectPanel, so:
first define a GameObject in the script, which levelSelectPanel is used to accept input from the panel

public GameObject levelSelectPanel;    //关卡按钮界面

The code to get the number of child objects where needed is as follows

unlockedLevelIndex = levelSelectPanel.transform.childCount;

Drag the levelSelectPanel object onto the object where this script is hung
insert image description here

Get parameters from other scripts

There are two methods, one is to search layer by layer through the parent, which saves resources, but cannot modify the parameter in the called script. The other is to store the parameters in memory, so that the first call is to create, and the second time is to read. The advantage of this method is that it is simple and convenient, and the parameter can be modified. The disadvantage is that there is a certain statement about the operation logic (read it if it has not been created). Another disadvantage is that it wastes resources.

the first method

int b = transform.Find("objectA").gameObject.GetComponent<ScriptA>().a;

The second method

int modleAmount = PlayerPrefs.GetInt("modleAmount",10);
PlayerPrefs.save();

Define a modleAmount variable, pass 10 to modleAmount
after creation, you can use PlayerPrefs.save(); to save the value in memory, if you don’t use this line of code, it will not be saved.

PlayerPrefs.DeleteKey("unlockedLevelIndex");

Delete the unlockedLevelIndex variable in memory

get script name

find the displayed object

 for(int i = 1;i<modleAmount +1 ;i++){
    
       //一个一个的进行判断看是否是激活的
            string customs = "modle["+i+"]";
            GameObject ParentObject = GameObject.Find("modle");    //找到modle的父级,然后查看谁是显示的
            GameObject ChildObject = ParentObject.transform.Find(customs).gameObject;       //找到   modle["+unlockedLevelIndex+"]  的物体
            if(ChildObject.activeInHierarchy == true){
    
    
            }
}

Show and hide objects

gameObject.SetActive(true);
gameObject.SetActive(false);

Guess you like

Origin blog.csdn.net/qq_19829077/article/details/130428469