Define and use any object from a certain class
My map has multiple objects and lights, but I do not know how to use these objects/lights in my C# class. How can I define these objects/lights and use a certain object/light by using its name. Like for example I have a Cube with a name "C1" and a Spotlight "S1" and how can I tell the class to use these certain objects.
Thanks in advance
Answer by Ahndrakhul · May 19, 2016 at 09:51 PM
I think this is what you are looking for. This is just an example of getting references to your scene objects using GameObject.Find, and then using those references to move things and change various properties.
using UnityEngine;
public class SampleClass : MonoBehaviour {
GameObject myCube;
GameObject mySpotlight;
Light spotlightLight;
void Start ()
{
myCube = GameObject.Find("C1");
mySpotlight = GameObject.Find("S1");
spotlightLight = mySpotlight.GetComponent<Light>();
ChangeLightColor(spotlightLight, Color.red);
}
void Update ()
{
myCube.transform.Translate(Vector3.up / 100);
mySpotlight.transform.Translate(Vector3.back / 100);
spotlightLight.intensity += .01f;
spotlightLight.range += .1f;
spotlightLight.spotAngle += .05f;
}
void ChangeLightColor(Light light, Color color)
{
spotlightLight.color = color;
}
}
You can also do this by making the fields (myCube, mySpotlight, Light) public and then dragging your objects onto the slots on the script in the inspector.
using UnityEngine;
public class SampleClass : MonoBehaviour {
public GameObject myCube;
public GameObject mySpotlight;
public Light spotlightLight;
void Start ()
{
ChangeLightColor(spotlightLight, Color.red);
}
void Update ()
{
myCube.transform.Translate(Vector3.up / 100);
mySpotlight.transform.Translate(Vector3.back / 100);
spotlightLight.intensity += .01f;
spotlightLight.range += .1f;
spotlightLight.spotAngle += .05f;
}
void ChangeLightColor(Light light, Color color)
{
spotlightLight.color = color;
}
}