- Home /
Creating a light in game C#
I i'm trying to create a light when triggerenter, but the only thing I found was creating a game object with mesh or a prefab... but I dont want to make a prefab because I want the light to have a color assigned already in other script. What I have now is a script that change a plane to random colors and I need to create a light with the same random color as the plane and placed at some distance over the plane transform.
Answer by robertbu · Jan 21, 2014 at 04:37 AM
You can create a light from scratch at runtime. You create a game object, position the game object, attach a Light component, then set the Light parameters. Exmaple:
#pragma strict
function Update() {
if (Input.GetKeyDown(KeyCode.A)) {
var go = new GameObject();
go.transform.position = Vector3(0,5,0);
var light = go.AddComponent(Light);
light.color = Color.red;
}
}
The default type for a new light is 'Point', but you can adjust that and other aspects of the Light component.
Note it would be easier to create a prefab of a light with all the setting you want. Then Instantiate() that prefab at the position you want and make any final light adjustments.
Thanks works fine, this is the final code in C#:
using UnityEngine;
using System.Collections;
public class changecolor : $$anonymous$$onoBehaviour
{
public Color[] colors;
private Vector3 positionxyz;
public Color Rcolor;
void OnTriggerEnter(Collider other)
{
Rcolor = colors[Random.Range(0, colors.Length)];
gameObject.renderer.material.color = Rcolor;
positionxyz = transform.position;
GameObject lightC = new GameObject();
lightC.name = "discolight";
lightC.AddComponent<Light>();
lightC.transform.position = positionxyz;
lightC.light.color = Rcolor;
lightC.light.range = 2.579712f;
lightC.light.intensity = 1;
lightC.light.render$$anonymous$$ode = LightRender$$anonymous$$ode.ForcePixel;
}
void OnTriggerExit(Collider other)
{
Destroy(GameObject.Find("discolight"));
}
}