- Home /
Broadcast Message using RaycastAll
there are two objects in the path of the Raycast that i need to destroy. The code starts with the function called "goprime()". from there it randomly decides if each direction will destroy the objects in front. i end up getting a null ref exception. here is the code
#pragma strict
var direction;
var did = false;
function Start () {
}
function Update () {
}
function goprime (){
if(!did){
did = true;
gonorth();
gosouth();
goeast();
gowest();
}
}
function gonorth(){
var number = Random.Range (1,3);
if(number < 2){
var hits : RaycastHit[];
if(Physics.RaycastAll(transform.position, Vector3.forward,8)){
for (var i = 0;i < hits.Length; i++) {
var hit : RaycastHit = hits[i];
hit.collider.BroadcastMessage ("die");
} }
}
}
function gosouth (){
var number = Random.Range (1,3);
if(number < 2){
var hits : RaycastHit[];
if(Physics.RaycastAll(transform.position, Vector3.back,8)){
for (var i = 0;i < hits.Length; i++) {
var hit : RaycastHit = hits[i];
hit.collider.BroadcastMessage ("die");
} }
}
}
function goeast(){
var number = Random.Range (1,3);
if(number < 2){
var hits : RaycastHit[];
if(Physics.RaycastAll(transform.position, Vector3.left,8)){
for (var i = 0;i < hits.Length; i++) {
var hit : RaycastHit = hits[i];
hit.collider.BroadcastMessage ("die");
} }
}
}
function gowest (){
var number = Random.Range (1,3);
if(number < 2){
var hits : RaycastHit[];
if(Physics.RaycastAll(transform.position, Vector3.left,8)){
for (var i = 0;i < hits.Length; i++) {
var hit : RaycastHit = hits[i];
hit.collider.BroadcastMessage ("die");
}
}}
}
Im getting a null ref exception when it tries to access the collider. it says collider isn't part of RaycastAll[].
Any and all help is appreciated. this is the last code i need to work for my game to be functional. if anyone has any thought at all please say it. i dont even care if its bone head stupid. it might be something dumb i missed.
Thanks =)
Answer by Tarlius · Feb 27, 2013 at 08:51 AM
You aren't assigning the return value for RaycastAll
var hits : RaycastHit[] = Physics.RaycastAll(transform.position, Vector3.left,8);
if(hits.Length > 0){
On a side note, you could simplify your code a fair bit by doing something like:
function GoDirection(dir : Vector3){
var number = Random.Range (1,3);
if(number < 2){
var hits : RaycastHit[] = Physics.RaycastAll(transform.position, dir,8);
if(hits.Length > 0){
for (var i = 0;i < hits.Length; i++) {
var hit : RaycastHit = hits[i];
hit.collider.BroadcastMessage ("die");
}
}
}
Then calling, for example:
void GoNorth() {
GoDirection(Vector3.forward);
}
On that note, your east and west both shoot left.
(Disclaimer: I don't speak js, but this should give you the idea)