Hello i need some help with a laser script
i have the laser working but i want to add a damage source so it applies constant dmg to the target
using UnityEngine;
using System.Collections;
public class LaserScript : MonoBehaviour
{
LineRenderer line;
public float m_MaxDamage = 1f;
void Start()
{
line = gameObject.GetComponent();
line.enabled = false;
}
void Update()
{
if (Input.GetButtonDown(“Fire1”))
{
StopCoroutine(“FireLaser”);
StartCoroutine(“FireLaser”);
}
}
IEnumerator FireLaser()
{
line.enabled = true;
while (Input.GetButton(“Fire1”))
{
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
line.SetPosition(0, ray.origin);
if (Physics.Raycast(ray, out hit, 100))
{
line.SetPosition(1, hit.point);
if (hit.rigidbody)
{
hit.rigidbody.AddForceAtPosition(transform.forward * 10, hit.point);
}
}
else
line.SetPosition(1, ray.GetPoint(100));
yield return null;
}
line.enabled = false;
}
}
this is the script it is c#
Hi Jrusso17,
Firstly, please use code tags as they increase the readability of your code on the forums: Using code tags properly - Unity Engine - Unity Discussions
As for your damaging, there are two ways you could go about this:
-
Although this method is generally frowned upon, you could call hit.transform.gameObject.SendMessage("Damage") within your while loop. This will go through all your scripts that you have attached onto your target and attempt to execute the “Damage” function, assuming you’ve implemented it. Generally not recommended as it can be quite slow.
-
You could ensure that any object you want to be damageable has a common script (you could use inheritance or interfaces here) that you can call a default “Damage” function on for example. It would go something like this.
public interface IDamageable {
void Damage(float damage);
}
Have a script on your targets that you want to be able to be damaged that uses this interface and implement the Damage function appropriately. An example would be the following (this is the script that goes on your enemy):
public class Enemy : MonoBehaviour, IDamageable {
public float health = 100;
public void Damage(float damage)
{
health -= damage;
}
}
Then in your while loop you can do something similar to:
while (Input.GetButton("Fire1"))
{
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
line.SetPosition(0, ray.origin);
if (Physics.Raycast(ray, out hit, 100))
{
line.SetPosition(1, hit.point);
if (hit.rigidbody)
{
hit.rigidbody.AddForceAtPosition(transform.forward * 10, hit.point);
}
IDamageable target = hit.transform.GetComponent<IDamageable>();
if (target != null)
target.Damage(10); // Replace this value with whatever damage you want to be dealt each frame.
}
else
line.SetPosition(1, ray.GetPoint(100));
yield return null;
}