Hi Guys,
Im very new to Unity3D and tried some Examples found here in the Forum.
My Goal is, to “AIM” an Object on Players Target (Center of the Screen)
I found this Code Example but it doesnt Work. I tried also the Examples in the Scripting Reference but always the same Error. (The Script is Attached to the Player Object)
var range = 40; // objects nearer than this are green
var rayLength = 200; // objects beyond this are not detected at all
private var hit : RaycastHit;
private var lastObj : Transform;
private var originalColor : Color;
private var ray : Ray;
function Update() {
// get a ray corresponding to the current camera's screen centre:
ray = Camera.main.ScreenPointToRay (Vector3(Screen.width/2,Screen.height/2));
// cast the ray and check if any enemies detected
if (Physics.Raycast (ray, hit, rayLength)) {
if (hit.transform.tag == "Enemy") {
CheckObject(hit); // enemy!
} else {
ResetLastObject(); // non-enemy under cursor
}
} else {
ResetLastObject(); // nothing under cursor
}
}
// this function determines whether to paint the object green or red
function CheckObject(hit : RaycastHit)
{
if (hit.transform != lastObj) {
// a new object detected
ResetLastObject();
// record original colour of new object
originalColor = hit.transform.renderer.material.color;
lastObj = hit.transform;
}
if (hit.distance < range) {
hit.transform.renderer.material.color = Color.Lerp(originalColor, Color.green, 0.5);
} else {
hit.transform.renderer.material.color = Color.Lerp(originalColor, Color.red, 0.5);
}
}
// this function restores the last detected object to its original colour
function ResetLastObject() {
if (lastObj != null) {
lastObj.renderer.material.color = originalColor;
lastObj = null;
}
}
The Error Appears at the Line:
ray = Camera.main.ScreenPointToRay (Vector3(Screen.width/2,Screen.height/2));
The Error: