- Home /
ScreenPointToRay
Can someone please help. i have this gun script that uses raycasting to shoot. it worked prefectly on my other project but when i imported it to the project that iam currently developing (witch is an online muliplayer project) it sent me an error when i launched it :
NullReferenceException UnityEngine.Camera.ScreenPointToRay (Vector3 position) (at C:/BuildAgent/work/842f9557127e852/Runtime/ExportGenerated/Editor/UnityEngineCamera.cs:267) gun.Update () (at Assets/gun.js:10)
You must post the script gun.js, where the error is occurring. Probably the camera variable you use with ScreenPointToView wasn't set - but we can only be sure if you show your script.
Answer by Rennat · Aug 23, 2011 at 07:57 PM
From the limited info given in the question it seems like you forgot to set a reference in the inspector or change a property name.
It's really hard to say without seeing the script but what that error may mean is when Unity tries to run UnityEngine.Camera.ScreenPointToRay ()
on line 10 of your script Assets/gun.js
that whatever you are passing what you think is a Vector3
object but when the code runs is null
. Sometimes adding `Debug.Log()` statements near the offending line and logging the variables to see if they really are what you think they are can help in finding where the problem actually originated.
the Input.mousePosition variable is a valide one and works in the Debug.Log() Statment. and also here is my script:
var spark : Transform;
var damage : int = 1;
var crossHairs : Texture;
var kills = 0;
private var nextFire : float = 0.0;
function Update(){
if(networkView.is$$anonymous$$ine){
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
var range = $$anonymous$$athf.Infinity;
if(Input.GetButton("Fire1")){
if(Time.time > nextFire){
nextFire = Time.time + 0.1;
if (Physics.Raycast (ray, hit, range)) {
Debug.DrawLine (ray.origin, hit.point);
spark.position = hit.point;
spark.light.enabled = true;
if(hit.collider.gameObject.tag == "Player"){
var enemyScript : health = hit.collider.gameObject.GetComponent("health");
enemyScript.health -= damage;
enemyScript.killer = this.transform;
}
spark.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
spark.particleEmitter.Emit();
}
}
}else{
spark.light.enabled = false;
}
}
}
function OnGUI(){
if(networkView.is$$anonymous$$ine){
GUI.DrawTexture(Rect(Screen.width/2 - 25,Screen.height/2 - 40,50,50),crossHairs);
GUI.Box(Rect(Screen.width-110,Screen.height-60,100,20), "$$anonymous$$ills: " + kills);
}
}