一、GameObject相关函数
函数 |
说明 |
GameObject() |
构造函数,创建GameObject |
SetActive() |
Activates/Deactivates 启用/停用 GameObject |
Destory() |
销毁GameObject启用/停用GameObject |
Instantiate() |
克隆函数,克隆一个Object到当前场景中 |
GetComponent<T>() |
通过GameObject实例获取组件 |
AddComponent<T>() |
给GameObject实例添加组件 |
SendMessage() |
调用GameObject的methodName方法 |
SendMessageUpwards() |
调用GameObject以及所有父物体的methodName方法 |
BroadcastMessage() |
调用GameObject以及所有子物体身上的methodName方法 |
注意:SendMessage方法,必须是GameObject身上挂载的脚本有methodName方法
具体使用方式:
1.定义两个对象
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Ryunm_ScriptsInUnity : MonoBehaviour
{
public GameObject qiaofeng;
public GameObject zhangwuji;
// Start is called before the first frame update
void Start()
{
//创建
GameObject newObj = new GameObject("xxx");
//启用
newObj.SetActive(true);
//克隆
GameObject cloneObj = Instantiate(newObj);
//添加组件
cloneObj.AddComponent<SpriteRenderer>();
//获取组件
var sr = cloneObj.GetComponent<SpriteRenderer>();
sr.sprite = firstSprite;
//销毁组件
Destroy(newObj,2);
}
// Update is called once per frame
//每帧都会执行一次
void Update()
{
//SendMessage执行游戏对象上的方法
if (Input.GetKeyDown(KeyCode.Q))
{
qiaofeng.SendMessage("GongFu_02");
}
if (Input.GetKeyDown(KeyCode.W))
{
qiaofeng.SendMessage("GongFu_01");
}
if (Input.GetKeyDown(KeyCode.E))
{
zhangwuji.SendMessage("GongFu_03");
}
if (Input.GetKeyDown(KeyCode.R))
{
zhangwuji.SendMessage("GongFu_04");
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ryunm_SendMessage : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void GongFu_01()
{
print("独孤九剑");
}
public void GongFu_02()
{
print("降龙十八掌");
}
public void GongFu_03()
{
print("九阳真经");
}
public void GongFu_04()
{
print("六脉神剑");
}
}