本文参考unity3dC#小白上手简单易懂(一)制作红绿灯【超简易版】
感谢博主
因为博主给出的是部分代码,这里记录一下详细版
1.交通灯制作
三个灯分别是ball1,ball2,ball3,我是先将ball1做好后,设为预制体,ball2和3都是复制的ball1,方便修改。
ball1设为Rigidbody,把重力选项取消勾选
文章图片
文章图片
材质:
文章图片
material,material1和material2的Shader设置如下:
文章图片
将代码挂载在TrafficLights上,并把对应的小球拖过去
文章图片
【Unity3d-2019.4-简易红绿灯】代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrafficLightsController : MonoBehaviour
{public Rigidbody b1,b2,b3;
//private float gtime = 4;
//绿灯亮4s
//private float ytime = 2;
//private float rtime = 4;
//private float darktime = 4;
//从第4s变黑
private float alltime = 10;
void Start()
{
Material material = new Material(Shader.Find("Legacy Shaders/Transparent/Diffuse"));
material.color = Color.black;
b1.GetComponent().material = material;
//开始时将灯设置为黑色
b2.GetComponent().material = material;
//开始时将灯设置为黑色
b3.GetComponent().material = material;
//开始时将灯设置为黑色InvokeRepeating("TurnGreen", 0f, alltime);
//0秒后调用TurnGreen() 函数,之后每10秒调用一次
InvokeRepeating("b1TurnBlack", 4f, alltime);
//绿灯灭InvokeRepeating("TurnYellow", 4f, alltime);
InvokeRepeating("b2TurnBlack", 6f, alltime);
InvokeRepeating("TurnRed", 6f, alltime);
InvokeRepeating("b3TurnBlack", 10f, alltime);
}
void TurnGreen()
{
Material material1 = new Material(Shader.Find("Legacy Shaders/Transparent/Diffuse"));
material1.color = Color.green;
b1.GetComponent().material = material1;
}void TurnYellow()
{
Material material1 = new Material(Shader.Find("Legacy Shaders/Transparent/Diffuse"));
material1.color = Color.yellow;
b2.GetComponent().material = material1;
}void TurnRed()
{
Material material1 = new Material(Shader.Find("Legacy Shaders/Transparent/Diffuse"));
material1.color = Color.red;
b3.GetComponent().material = material1;
}void b1TurnBlack()
{
Material material2 = new Material(Shader.Find("Legacy Shaders/Transparent/Diffuse"));
material2.color = Color.black;
b1.GetComponent().material = material2;
}
void b2TurnBlack()
{
Material material2 = new Material(Shader.Find("Legacy Shaders/Transparent/Diffuse"));
material2.color = Color.black;
b2.GetComponent().material = material2;
}
void b3TurnBlack()
{
Material material2 = new Material(Shader.Find("Legacy Shaders/Transparent/Diffuse"));
material2.color = Color.black;
b3.GetComponent().material = material2;
}
}
推荐阅读
- Unity|Unity C# 网络学习(十一)——自定义协议生成工具
- unity|Unity3D协程详解
- Unity功能|Unity之UGUI-特效遮挡问题2.0
- 从头构筑C#知识体系|【从头构筑C#知识体系】1.9 特性
- Unity|Unity UGUI ScrollView滑动到指定位置
- Unity|Unity 获取设备信息
- Unity|Unity Spine播放动画、动画播放结束回调、停止播放
- U3D|Unity接入穿山甲广告SDK教程
- unity|unity开发微信小游戏1