This is my first real attempt at coding for unity. Well, I used someone else’s code as my base but changed it quite a bit. Basically, it’s a code to make items in the game clickable and gives the player choices based on what they click. Then it clears out the variables (to clear the GUI text) on a timer. I’m far from done with it but want some help cleaning it up before I go on. It “works” but I know my code is sloppy and probably has some problems with it I haven’t yet discovered. What I have discovered is sometimes the “clearVar” function runs when I don’t want it to rather than timed like I want it. If there is a better way to clear the variables/GUI text after a few seconds, please tell me…
And before anyone asks “why did you do X that way and not this way”, I did it this way because it’s the only way I currently know how to do it… But I’m learning! Anyway, here is my sloppy code:
var target1: Transform;
var target2: Transform;
var whatHit = 0;
var playerAction = 0;
var playerResponse = 0;
function Update () {
if (Input.GetMouseButton(0)) {
var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit: RaycastHit;
if (Physics.Raycast(ray, hit)) {
if (hit.transform == target1) {
print("Hit target 1");
whatHit = 1;
//print(whatHit);
playerResponse = 0;
} else if (hit.transform == target2) {
print("Hit target 2");
whatHit = 2;
playerResponse = 0;
}
} else {
print("Hit nothing");
whatHit = 0;
playerResponse = 0;
}
}
if (playerAction == 1) {
if (Input.GetKeyDown("y")) {
playerResponse = 1;
}
else if (Input.GetKeyDown("u")) {
playerResponse = 2;
}
if (Input.GetKeyDown("i")) {
playerResponse = 3;
}
}
}
function OnGUI () {
if (whatHit == 1) {
GUI.Label(Rect(10,10,300,200), "You clicked the cube");
GUI.Label(Rect(10,30,300,200), "Press Y to attack");
GUI.Label(Rect(10,50,300,200), "Press U to talk");
GUI.Label(Rect(10,70,300,200), "Press I to ignore");
playerAction = 1;
}
else if (whatHit == 2){
GUI.Label(Rect(10,10,300,200), "You clicked the ground");
playerResponse = 0;
}
else if (whatHit == 0){
GUI.Label(Rect(10,10,300,200), " ");
playerResponse = 0;
}
if (playerResponse == 1) {
GUI.Label(Rect(10,90,300,200), "You attack the cube");
Invoke("clearVars", 2);
}
else if (playerResponse == 2) {
GUI.Label(Rect(10,90,300,200), "Hello Cube!");
Invoke("clearVars", 2);
}
else if (playerResponse == 3) {
GUI.Label(Rect(10,90,300,200), "You ignore the cube");
Invoke("clearVars", 2);
}
else if (playerResponse == 0) {
GUI.Label(Rect(10,90,300,200), " ");
}
}
function clearVars () {
whatHit = 0;
playerAction = 0;
playerResponse = 0;
}
Thanks!