public class Raycaster : MonoBehaviour {
public GameObject Cracked;
public void Crash(){
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.forward, out hit)) {
if(hit.collider.gameObject.tag == "Crash")
{
if(Vector3.Distance(transform.position,hit.collider.transform.position) <= 3)
{
Instantiate(Cracked,hit.collider.gameObject.transform.position,hit.collider.gameObject.transform.rotation);
Destroy(hit.collider.gameObject);
Debug.Log ("Crushed!");
}
}
}
}
}
As you see my code has no errors!
But when I try it in the game it works only on one cube tagged “Crash”.
I double-checked tags and it’s all ok
But when i try to ‘break’ the other cube it doesn’t work.
Raycast doesn’t even hit it!
BTW I have a gameObject and this script attached to it.I am making a 3rd Person game so I can’t use Camera.main.transform.position.
You could store the position of the object you want to destroy in variables, destroy it and only then instantiate the Cracked object on the stored vectors.
using UnityEngine;
using System.Collections;
public class Raycaster : MonoBehaviour {
public GameObject Cracked;
public Vector3 instPos;
public Vector3 instRot;
public void Crash()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.forward, out hit, 3))
{
if(hit.collider.gameObject.tag == "Crash")
{
instPos = hit.collider.gameObject.transform.position;
instRot = hit.collider.gameObject.transform.eulerAngles;
Destroy(hit.collider.gameObject);
GameObject instGO = Instantiate(Cracked, instPos);
instGO.transform.eulerAngles = instRot;
Debug.Log ("Crushed!");
}
}
}
}
Try that out, and if it doesn’t work, which I can’t guarantee it will, then keep trying on that same road and you will get somewhere. Good luck with the game, mate.
If the same code doesn’t work on two different, but “identical” objects, then those objects are not identical. Are you using prefabs? Revert them and see if they work then. Make sure both have colliders, and their tags are the same “Crash” Your original code also does a distance check - maybe the other cube is just too far away?
As a general tip, try making your debug messages more helpful. For instance, you could debug log the name of the object you hit instead of the generic “Crushed” message. Maybe you’re not hitting the object you think you are hitting. You’re assuming that when it says “Crushed” you hit a particular object, but you aren’t doing anything to verify that.