一、GmaeObject独有的静态方法
CreatePtimitive
Find比较耗费性能
FindGameObjectsWithTag
FindWithTag
public class API03GameObject : MonoBehaviour
{
//查找物体的方法
//1.GameObject go = GameObject.Find("Main Camera");
//go.SetActive(false);
//GameObject[] gos= GameObject.FindGameObjectsWithTag("Main Camera");
//做空判断
//gos[0].SetActive(false);
GameObject go= GameObject.FindGameObjectWithTag("Main Camera");
go.SetActive(false);
}
}
二、游戏物体间消息的发送和接收
BroadCastMessage(广播消息)不光会调用自身,还会查找子物体的消息并调用 本质还是调用方法
SendMessage(发送消息)只会搜寻当前物体上的方法
SendMessageUpwards(向上发送消息)当前物体以及他的父亲
public class API04Message : MonoBehaviour
{
public GameObject target;
void Start ()
{
//target.BroadcastMessage("Attack",null,SendMessageOptions.DontRequireReceiver);//一般是调用某个方法(如果后面不写其他参数,又没有信息接受者,会报错)第二个选项默认为空,第三个选择没有接受者,这时即使没有接收者也不会报错
//target.SendMessage("Attack", null, SendMessageOptions.DontRequireReceiver);
target.SendMessageUpwards("Attack", null, SendMessageOptions.DontRequireReceiver);
}//接收消息只需要定义一个跟Attack一样的方法就行
}
挂到cube上的
public class Cube : MonoBehaviour
{
void Attack()
{
Debug.Log(this.gameObject+"正在进行攻击");
}
}
三、得到组件的各种方法函数
GetComponent
GetComponents
GetComponentInChildren
GetComponentsInChildren
GetComponentInParent
GetComponentsInParent
例子:
public class API05GetComponent : MonoBehaviour
{
public GameObject target;
void Start ()
{
Cube cube= target.GetComponent<Cube>();
Transform t =target.GetComponent<Transform>();
Debug.Log(cube);
Debug.Log(t);
Debug.Log("--------------------------------");
Cube[] cubes = target.GetComponents<Cube>();
Debug.Log(cubes.Length);
Debug.Log("--------------------------------");
cubes = target.GetComponentsInChildren<Cube>();
foreach (Cube c in cubes)
{
Debug.Log(c);
}
Debug.Log("--------------------------------");
cubes = target.GetComponentsInParent<Cube>();
foreach (Cube c in cubes)
{
Debug.Log(c);
}
}
}
四、MonoBehaviour里面常用变量
isActiveAndEnabled
enabled
name
tag
gameObject
transform
public class API06MonoBehaviour : MonoBehaviour
{
public Cube cube;
void Start ()
{
Debug.Log(this.isActiveAndEnabled);//判断自身是否激活
Debug.Log(this.enabled);//判断自身是否激活
enabled = false;
Debug.Log(name);
Debug.Log(tag);
Debug.Log(gameObject);
Debug.Log(transform);
print("hahaha");
Debug.Log(cube.isActiveAndEnabled);
Debug.Log(cube.enabled);
enabled = false;//禁用方法禁用的是update,但现在没有update,所以编辑里脚本上没有对号
Debug.Log(cube.name);
Debug.Log(cube.tag);
Debug.Log(cube.gameObject);
Debug.Log(cube.transform);
}
}
五、MonoBehaviour中Invoke的使用
CancelInvoke
Invoke
InvokeRepeating
IsInvoke
public class API07Invoke : MonoBehaviour
{
void Start ()
{
//Invoke("Attack",3);//多少秒之后调用
InvokeRepeating("Attack",4,2);//四秒之后开始,每间隔2秒调用
CancelInvoke("Attack");//如果不指定名字就取消所有的
}
void Update()
{
bool res= IsInvoking("Attack");
print(res);
}
void Attack()
{
print("攻击目标");
}
}