- Home /
Destroying gameobject
Im new to unity and wanted to make a simple game where i have to shoot some cubes. But i run into 2 problems. problem 1) If i shoot at a cube and keep shooting it, my score increases every frame and not just 1 time. problem2) i wanted to solve this and tried to destroy the cube after it was hit. But i dont know how i can destroy the cube not the bullet.
Here my code
using UnityEngine;
using System.Collections;
public class LaserScript : MonoBehaviour {
LineRenderer line;
public int weaponPower = 10;
public int score = 0;
void Start ()
{
line = gameObject.GetComponent<LineRenderer> ();
line.enabled = true;
gameObject.GetComponent<LensFlare> ().enabled = false;
Screen.lockCursor = true;
}
void Update ()
{
if (Input.GetButtonDown ("Fire1"))
{
StopCoroutine("FireLaser");
StartCoroutine("FireLaser");
}
if (score == 10)
{
Debug.Log ("You Won");
}
}
IEnumerator FireLaser()
{
line.enabled = true;
gameObject.GetComponent<LensFlare> ().enabled = true;
while (Input.GetButton("Fire1"))
{
line.renderer.material.mainTextureOffset = new Vector2(0,Time.time);
Ray ray = new Ray(transform.position,transform.forward);
RaycastHit hit;
line.SetPosition(0,ray.origin);
if(Physics.Raycast(ray,out hit,3000))
{
line.SetPosition(1,hit.point);
if(hit.rigidbody)
{
hit.rigidbody.AddForceAtPosition(transform.forward*weaponPower,hit.point);
score++;
Debug.Log(score);
}
}
else
line.SetPosition(1,ray.GetPoint(3000));
yield return null;
}
line.enabled = false;
gameObject.GetComponent<LensFlare> ().enabled = false;
}
}
Hopefully someone can help me. And sorry for my bad english ;)
Answer by PippyLongbeard · Dec 02, 2013 at 03:39 AM
Well, as to your second problem, in the 'if' statement at line 50 add this:
Destroy(hit.transform.gameObject);
This will destroy whatever rigidbody your ray hit.
Answer by $$anonymous$$ · Dec 02, 2013 at 06:59 AM
Thanks, I will try you addition to my code as soon as i am at home.But one more question, is there a way that it only destroys a gamobjet with a spacial tag? So it destroys objects with a rigidbody an for example the tag 'cube'