Common methods in GameObject in Unity

1. Static method

(1) Find objects based on object name (game object)

        GameObject obj2 = GameObject.Find("Holens");
        if( obj2 != null )
        {
            print(obj2.name);
        }
        else
        {
            print("没有找到对应对象");
        }

(2) Find objects through tags
   

GameObject obj3 = GameObject.FindWithTag("Player");

(3) Find multiple objects

GameObject[] objs = GameObject.FindGameObjectsWithTag("Player");
print("找到tag为Player对象的个数" + objs.Length);

! ! ! Note: None of these methods can find deactivated objects! ! !

(4) Destroy objects

        GameObject.Destroy(myObj2);
        //第二个参数 代表延迟几秒钟删除
        GameObject.Destroy(obj5, 5);
        //Destroy不仅可以删除对象 还可以删除脚本
        GameObject.Destroy(this);

If the class inherits Mono, you don’t need to write GameObject.

2. Member method

(1) Add a script to the object

Lesson2 les2 = obj6.AddComponent<Lesson2>();

(2) Label comparison

        if(this.gameObject.CompareTag("Player"))
        {
            print("对象的标签 是 Player");
        }

(3) Set activation and deactivation

obj6.SetActive(false);
obj6.SetActive(true);

 

Guess you like

Origin blog.csdn.net/holens01/article/details/132635819