0
\$\begingroup\$

I want to create a traffic light for a Unity3D game. I will model it in blender.

What is the best way to control this light in a unity scene?

One way I could think of is to change texture of say red light from dull red to bright red, when it is time for red signal. But I am not sure if this is possible or a good strategy.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You can access the material of the lamp object in the Unity-API.

public GameObject lampObject;
public bool isGreen;
public Color greenColor, redColor;

private void Update()
{
    lampObject.material.color = isGreen ? greenColor : redColor;
}

This will set the material color of the lamp to a specified value you can edit in the inspector. It is also possible to lerp to the target color with Color.Lerp.

var targetColor = isGreen ? greenColor : redColor;
lampObject.material.color = Color.Lerp(lampObject.material.color, targetColor, 0.1f);

The 0.1f will control how fast the color will blend to the target color.

Other possible ways would be -as you said- changing the texture of the lamp object texture by accessing lampObject.material.mainTexture but I dont see any reasons to change the whole texture just for a traffic lamp color.

\$\endgroup\$
5
  • \$\begingroup\$ Thanks! So if I want to simply modify the material color, do I still apply texture on the lamp? It would be great if you could describe the workflow from Blender. \$\endgroup\$ Jul 4, 2015 at 10:05
  • \$\begingroup\$ The workflow from Blender would be the same as before. You dont even have to select a color there, also if you dont want to change textures (i cant remember any reason to do that) you can leave UV maps away. In Unity the materials are simple containers for shaders and their properties and one of these propierties is the color which I changed in my answer. So this is everything you need and you can work in Blender as you always did before. \$\endgroup\$ Jul 4, 2015 at 10:14
  • \$\begingroup\$ Was this helpful or should I explain unclear stuff? \$\endgroup\$ Jul 5, 2015 at 6:30
  • \$\begingroup\$ Your approach worked fine. However for Unity 5.1 I had to write lampRed.GetComponent<Renderer>().material.color = new Color (240, 0, 0);. Also just setting the material's color makes it look rather flat. I might try something with texture to give the lamp some depth. Thanks, I am accepting your answer. \$\endgroup\$ Jul 5, 2015 at 8:23
  • \$\begingroup\$ Good to hear you figured it out, I really have to update my Unity. \$\endgroup\$ Jul 5, 2015 at 9:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .