unity学习——委托delegate的使用

初次接触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的移动。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值