1.组件的调用
例如:AudioSource组件
AudioSource audio = this.GetComponent<AudioSource>();//获取组件
audio.play();//播放
void Update()
{
if(Input.GetMouseButtonDown( 0 ))
{
PlayMusic();
}
}
void PlayMusic()
{
// 获取组件
AudioSource audio = this.GetComponent<AudioSource>();
if( audio.isPlaying )
{
Debug.Log("* 停止播放");
audio.Stop();
}
else
{
Debug.Log("* 开始播放音乐 ..");
audio.Play();
}
}
2.调用其他节点的组件
定义一个相应的组件类型,拖入相关节点后,unity会自动引入
public AudioSource audio;
3.引用脚本组件
这是一个简单的引用其他节点脚本组件的例子,这是一个主控节点,总共引用了四个脚本组件。
//主控节点
public class MainControl : MonoBehaviour {
//引用脚本组件
public Fan fan;
public AudioSource audio;
public Fly fly;
public FlyTurn turn;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space)) //按空格键触发事件
{
PlayMusic();//调用函数
}
DoWork();
}
void DoWork() {
if(fan.rotateSpeed == 0)
{
fly.xSpeed = 0;//引用其他脚本组件的参数
fly.zSpeed = 0;
}
else
{
fly.zSpeed = 0;
fly.xSpeed = 0;
turn.turnSpeed = 0;
if (Input.GetKey(KeyCode.W)) fly.zSpeed = 50;
if (Input.GetKey(KeyCode.S)) fly.zSpeed = -50;
if (Input.GetKey(KeyCode.D)) fly.xSpeed = 50;
if (Input.GetKey(KeyCode.A)) fly.xSpeed = -50;
if (Input.GetKey(KeyCode.Q)) turn.turnSpeed = 30;
if (Input.GetKey(KeyCode.E)) turn.turnSpeed = -30;
}
}
void PlayMusic()
{
if (audio.isPlaying)
{
audio.Stop();
fan.rotateSpeed = 0;
}
else
{
audio.Play();
fan.rotateSpeed = 1000;
}
}
4.消息调用
这是另外一种实现调用其他脚本组件的方法,具体步骤:
(1)主控节点使用全局变量先声明一个节点变量:
public GameObject fanNode;
(2)在updata()函数下向该节点发送“消息”:
fanNode.SendMessage("对应节点下的某个函数名");
这个方法其实运用了“反射机制”,要求函数名必须与对应的节点下的函数名一致,才会调用相应的函数。