- Home /
Help with a Script in C# for shooting and lighting
Hey everyone basically I need a C# script for hitting object with bullet so when it hits above the object will appear area light. This is what I've got.
using UnityEngine; using System.Collections;
public class ThermalDetonator : MonoBehaviour {
float lifespan = 3.0f;
public GameObject light_prefab;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update (){
if(gameObject.tag == "Enemy") {
gameObject.tag = "Untagged";
Instantiate(light_prefab, transform.position, Quaternion.identity);
}
}
}
and this is attached to Bullet prefab that my PC shoots with. And I want it to make so when it hits "target" the name of object tagged as "Enemy" the area light will appear around it and if possible it will go off after lets say 30 second. If anyone could help me with that. I do realize that this script might be useless. Thank you.
ok so you want light to appear when a bullet hits something? what are you trying to do? is this for a sticky grenade type of thing? your Update code doesn't make sense to me.
Answer by GerardD · Dec 05, 2013 at 04:36 AM
One approach would be to have a collider on the enemy object that should it be hit by a bullet, it activates an attached light.
This is a quick attempt at a script that would be attached to an enemy. When the enemy trigger is hit by the bullet, then it would activate the light.
public class Enemy : MonoBehaviour {
//This is the length of time the light will be on for
public float lightDuration;
private Light areaLight;
void Start () {
//This allows you to access the light that is attached to the enemy
areaLight = GetComponent<Light>();
//Ensures that the light is off be default if you haven't set it up this way
areaLight.enabled = false;
}
void Update() {
//Used for testing - this would be removed
if (Input.GetKeyDown(KeyCode.Space)) {
TurnLightOn();
}
}
//When the trigger is hit by the bullet
void OnTriggerEnter(Collider other) {
//The collider of the bullet has hit the enemy
if (other.gameObject.tag == "bullet") {
TurnLightOn();
}
}
private void TurnLightOn() {
StartCoroutine(ActivateLight());
}
private IEnumerator ActivateLight() {
//This will turn the light on
light.enabled = true;
//This will cause this function to wait for the light duration
//whilst still allowing the engine execution to continue
yield return new WaitForSeconds(lightDuration);
//This will turn the light off
light.enabled = false;
}
}
This could be attached to whatever GameObject you wanted to have a switch able light on. You might wish to change the logic that calls the TurnLightOn function.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Hey can anyone help with a shooting script??? 0 Answers
Bullets sometimes shoot under map 1 Answer
Shoot Script Help 1 Answer
Shooting speed help! 1 Answer