If float “angle” should be a variable. why is it Debug.Log(); as a object that I can not
use.
The script should take the vector3s and return the angle of the 2 objects. Then round to nearest hole number and display it on screen, It failed. To remove
public float angle =0; gives multiple errors.To use the script as is: Dose nothing. some times it said the angle is populated but value is never used.
using UnityEngine;
using System.Collections;
public class Target_Indicator : MonoBehaviour
{
public Transform target; //values that will be set in the Inspector.
public float angle = 0; //Create sting, Now we can see it in the inspector.
void Update()
{
Vector3 targetDir = target.position - transform.position;
Vector3 forward = transform.forward;
float angle = Vector3.Angle(targetDir, forward);
}
void OnGUI()
{
float displayValue = Mathf.Round(angle);//Change decimal to hole numbers.
//Make a GUI label - position on sccreen - add "angle:" - display the value.
GUI.Label(new Rect(30, 475, 150, 50), "angle: " + displayValue.ToString());
}
}
So what is going on with the value “angle” that I can not use it to display in the inspector or on screen.
You’re storing the angle calculated in Update in a temporary variable angle - the variable angle you’ve defined at the beginning isn’t ever affected. Temporary variables are those declared inside a function: they exist only while the function is running, and are destroyed upon return.
To solve the problem, just remove the float declaration before angle in Update:
EDITED: If you’re using planes for the indicator and compass, set the indicator Y angle to the angle found. You should also remove height differences from the direction vector to keep it strictly horizontal, like below:
public Transform indicatorPlane; // drag the indicator here
void Update()
{
Vector3 targetDir = target.position - transform.position;
Vector3 forward = transform.forward;
targetDir.y = 0; // remove any height difference
angle = Vector3.Angle(targetDir, forward);
indicatorPlane.eulerAngles = Vector3(0, angle, 0);
}
But this isn’t the best way to display an on-screen compass - usually this is done in OnGUI: draw the compass texture, rotate the gui matrix with GUIUtility.RotateAroundPivot, draw the indicator texture, then restore the gui matrix - something like this:
public Rect rCompass = new Rect(30, 400, 80, 80); // compass position/size
public Texture2D compass;
public Texture2D indicator;
void Update()
{
Vector3 targetDir = target.position - transform.position;
Vector3 forward = transform.forward;
targetDir.y = 0; // remove any height difference
angle = Vector3.Angle(targetDir, forward);
}
void OnGUI(){
GUI.DrawTexture(rCompass, compass); // draw the compass
Matrix4x4 curMatrix = GUI.matrix; // save cur matrix
GUIUtility.RotateAroundPivot(angle, rCompass.center); // rotate gui matrix
GUI.DrawTexture(rCompass, indicator); // draw indicator
GUI.matrix = curMatrix; // restore matrix (no rotation)
}