- Home /
New to Raycasts, trouble using "hit"
So I've been trying to get the hang of Raycasts for about a week now (slow learner) and I've finally gotten to the point where I can make my mouse tell me whether or not it's on top of something but now I'm trying to make it minus 1 from a variable containing the "enemy's" (cube's) life. The cube has 2 life and every time I click him it should subtract one and then once his life is zero it should print: "cube is dead" but I must be writing something wrong with the "hit" part because if I comment that part out the part that tells me the thing about where the mouse is works fine. Also just a warning in advance I'm away from home and so all I have to learn with is a crappy little netbook and the box with the code formatting literally won't load... I'm so sorry and as soon as I get back (in two days, I'd also do it now but I don't know BB code which I at least think is what these forums use) I'll make sure to format it correctly on my usual computer but for now here's the code (I'm really sorry if it's a bitch to read...) EDIT: I reloaded the page a couple of times and the buttons appeared so I think the code should be fine now, here it is:
#pragma strict
var enemyLife : float = 2;
function Update () {
if(Input.GetMouseButton(0)){
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast (ray, hit)){
print("hit");
}
else{
print("did not hit");
}
}
if(hit.transform.tag == "enemy"){
enemyLife = enemyLife--;
print("tag is not the problem");
}
if (enemyLife == 0){
print("cube is dead");
}
}
The part where it says:
if(hit.transform.tag == "enemy"){
enemyLife = enemyLife--;
print("tag is not the problem");
}
originally said:
if(hit.collider.tag == "enemy"){
enemyLife = enemyLife--;
print("tag is not the problem");
}
I watched a tutorial and decided to change it.
"I must be writing something wrong with the "hit" part because if I comment that part out the part that tells me the thing about where the mouse is works fine"... you've failed to describe what happens if you don't comment out "the hit part", and what part is that anyway? Commenting out line 6, for example, should give you an error.
Sorry, I think the part I was referring to was lines 15-21 or at least the problem arose when I wrote that part. and what happens if I leave it? This : NullReferenceException: Object reference not set to an instance of an object NewBehaviourScript.Update () (at Assets/NewBehaviourScript.js:15)
I should have originally included that, sorry. It's the error message I get for doing something wrong.
Also I haven't ever even heard of On$$anonymous$$ouseUp I'll look it up in the scripting reference.