Unity3d-2019.4-简易红绿灯

本文参考unity3dC#小白上手简单易懂(一)制作红绿灯【超简易版】
感谢博主
因为博主给出的是部分代码,这里记录一下详细版
1.交通灯制作
三个灯分别是ball1,ball2,ball3,我是先将ball1做好后,设为预制体,ball2和3都是复制的ball1,方便修改。
ball1设为Rigidbody,把重力选项取消勾选
Unity3d-2019.4-简易红绿灯_第1张图片
Unity3d-2019.4-简易红绿灯_第2张图片
材质:Unity3d-2019.4-简易红绿灯_第3张图片
material,material1和material2的Shader设置如下:
在这里插入图片描述

将代码挂载在TrafficLights上,并把对应的小球拖过去
Unity3d-2019.4-简易红绿灯_第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<MeshRenderer>().material = material;//开始时将灯设置为黑色
        b2.GetComponent<MeshRenderer>().material = material;//开始时将灯设置为黑色
        b3.GetComponent<MeshRenderer>().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<MeshRenderer>().material = material1;
        }

    void TurnYellow()
    {
        Material material1 = new Material(Shader.Find("Legacy Shaders/Transparent/Diffuse"));
        material1.color = Color.yellow;
        b2.GetComponent<MeshRenderer>().material = material1;
    }

    void TurnRed()
    {
        Material material1 = new Material(Shader.Find("Legacy Shaders/Transparent/Diffuse"));
        material1.color = Color.red;
        b3.GetComponent<MeshRenderer>().material = material1;
    }

    void b1TurnBlack()
    {
        Material material2 = new Material(Shader.Find("Legacy Shaders/Transparent/Diffuse"));
        material2.color = Color.black;
        b1.GetComponent<MeshRenderer>().material = material2;
    }
    void b2TurnBlack()
    {
        Material material2 = new Material(Shader.Find("Legacy Shaders/Transparent/Diffuse"));
        material2.color = Color.black;
        b2.GetComponent<MeshRenderer>().material = material2;
    }
    void b3TurnBlack()
    {
        Material material2 = new Material(Shader.Find("Legacy Shaders/Transparent/Diffuse"));
        material2.color = Color.black;
        b3.GetComponent<MeshRenderer>().material = material2;
    }
}

你可能感兴趣的:(unity)