初次接触c#的委托机制,感觉非常方便使用,下面是一个简单的委托使用的例子。
目的:实现按下键盘上左右键能使三个cube物体同时移动
1.首先创建一个unity场景(非常简单包括一个主相机,三个cube物体cube1,cube2,cube3)
2.建立两个C#脚本,一个名为SmartCube,另一个名为CubeManager
SmartCube的代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SmartCube : MonoBehaviour {
public float speed = 10;
public void MoveHorizontal()
{
transform.Translate(Time.deltaTime*speed*Input.GetAxis("Horizontal"),0,0);
}
}
CubeManager代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeManager : MonoBehaviour {
delegate void CubeMoveHDelegate();
CubeMoveHDelegate hDelegate;
// Use this for initialization
void Start () {
SmartCube[] cubes= FindObjectsOfType(typeof(SmartCube))as SmartCube[];
for (int i = 0; i < cubes.Length; i++)
{
SmartCube c = cubes[i];
hDelegate += c.MoveHorizontal;
}
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow))
hDelegate();
}
}
3.将SmartCube脚本拖分别拖到三个cube物体上,将CubeManager拖到主相机上,调整好相机角度便于观察cube的移动。