Jump to content

A bit of help in Unity java?

Meowingtonhaxor

So I'm making kind of a slender game, but you to collect runestones instead of pages, when i have tried the script I will post in a second nothing seems to work, ANy help would be appreciated seeing as it's my final for the class. Thanks!

var rocks : int = 0;var rocksToWin : int = 8;var distanceToRock : float = 4;function Start () {Screen.lockCursor = true;}function Update(){if(Input.GetKeyDown(KeyCode.E)) var ray = Camera.main.ScreenPointToRay(Vector3(Screen.width * 0.5, Screen.height * 0.5, 0));var hit : RaycastHit;if(Physics.Raycast(ray, hit, distanceToRock))if(hit.collider.gameObject.tag == "rock")rocks += 1;Debug.Log("a rock was picked up. Total rocks =" + rocks);if(rocks >= rocksToWin);Application.loadLevel(0);}
Link to comment
Share on other sites

Link to post
Share on other sites

Your code is rather confusing... the if statements have nothing underneath them to execute? Your basically asking the computer "if the user presses 'E' nothing happens". What is your goal to accomplish with this script?

Link to comment
Share on other sites

Link to post
Share on other sites

It would be nice if you would use proper indentation to make it easier for us to read. Also, do you mean Javascript? I didn't think unity worked with Java, also your syntax doesn't look right for it to be Java. Note that Java and Javascript are two very different languages and you shouldn't get them mixed up. Googling a question in Java when you want an answer in Javascript might not help you much ;)

 

Anyway, because you don't use brackets on your if statements, this is what your code looks like

function Update(){    if(Input.GetKeyDown(KeyCode.E))         var ray = Camera.main.ScreenPointToRay(Vector3(Screen.width * 0.5, Screen.height * 0.5, 0)); // executed in the if statement so "ray" loses scope for the rest of the function    var hit : RaycastHit;    if(Physics.Raycast(ray, hit, distanceToRock)) // "ray" is not in scope so this would have an error        if(hit.collider.gameObject.tag == "rock") // executes if the Raycast if statement is true            rocks += 1; // executes if the collider if statement is true    Debug.Log("a rock was picked up. Total rocks =" + rocks);    if(rocks >= rocksToWin); // this doesn't do anything    Application.loadLevel(0);}
Link to comment
Share on other sites

Link to post
Share on other sites

Your code is rather confusing... the if statements have nothing underneath them to execute? Your basically asking the computer "if the user presses 'E' nothing happens". What is your goal to accomplish with this script?

 

 

It would be nice if you would use proper indentation to make it easier for us to read. Also, do you mean Javascript? I didn't think unity worked with Java, also your syntax doesn't look right for it to be Java. Note that Java and Javascript are two very different languages and you shouldn't get them mixed up. Googling a question in Java when you want an answer in Javascript might not help you much ;)

 

Anyway, because you don't use brackets on your if statements, this is what your code looks like

 

I'm a bit new to coding, sorry

Link to comment
Share on other sites

Link to post
Share on other sites

I'm a bit new to coding, sorry

Berhaps just to mention.

If you use IF statement WITHOUTH curly brackets :  {  }  =  When IF is triggered only thing that will be executed under the statement condition is the first line of code in if statement

so basically if your statement is :

if (x>5)

print("x is larger than 5");

print("5 is lower than x");

 

 

This will be the output if x = 6:

6 is larget than 5

5 is lower than 6.

 

yea nothing is wrong.

But if we change the X to be x =  2 the output will be  ;

 

5 is lower than 2.

 

 

 

See?

However if you use the brackets.  Everything IN the brackets gets executed under the IF statement conditions.

Link to comment
Share on other sites

Link to post
Share on other sites

First off, ITS JAVASCRIPT!!! BLARG!! (OR UNITYSCRIPT)

 

Now that I have that out of the way : here are some tips from a fellow long time Unity user.

 

#1 Use {} in all your statements. 

basically what SirPaul said xD

 

 

 

#2 : == is evil. 

JavaScript tries to be "easy" and "forgiving", and often falls flat on its face because of it. The problem is == evaluates both TRUE statements (Like 1 == 1)  and TRUETHY statements (like 1 == "1") the same. This gets out of hand pretty quickly as it unpredictable.  

'' == '0'           // false 0 == ''             // true 0 == '0'            // true : this should be falsefalse == 'false'    // false false == '0'        // true : this should be falsefalse == undefined  // false : this would be true in most everything other FOO language then JS false == null       // falsenull == undefined   // true var a = [1,2,3];var b = [1,2,3];a == b            // false : This should be TRUE Following JS's logic a === b           // false

You are better off using === . While it may be harder to work with, you will avoid one of the worst part of JavaScript!

 

 

#3 Always put all your VAR ('s) at the top of the function.

In Javascript, there is no performance improvements by creating variables in a lower scope. So your function should look something like this. 

function Update(){     var ray;    if(Input.GetKeyDown(KeyCode.E)){        ray = Camera.main.ScreenPointToRay(Vector3(Screen.width * 0.5, Screen.height * 0.5, 0));    }    if(Physics.Raycast(ray, hit, distanceToRock)){    //Do_stuff!    }} 
Link to comment
Share on other sites

Link to post
Share on other sites

 

#2 : == is evil. 

JavaScript tries to be "easy" and "forgiving", and often falls flat on its face because of it. The problem is == evaluates both TRUE statements (Like 1 == 1)  and TRUETHY statements (like 1 == "1") the same. This gets out of hand pretty quickly as it unpredictable.  

0 == '0'            // true : this should be falsefalse == '0'        // true : this should be falsefalse == undefined  // false : this would be true in most everything other then JS  var a = [1,2,3];var b = [1,2,3];a == b            // false (This should be TRUE) 

You are better off using === . While it may be harder to work with, you will avoid one of the worst part of JavaScript!

 

 

It don't quite see how this is a problem.

If you are comparing different datatypes or undefined variables, then it's your fault as a programmer do not take care of it and not the one of JS.

and no imho a and b should not be the same when you give a little about OO.

Mini-Desktop: NCASE M1 Build Log
Mini-Server: M350 Build Log

Link to comment
Share on other sites

Link to post
Share on other sites

#1 Use {} in all your statements. 

basically what SirPaul said xD

Fiddled with my code a bit, here it is now. Still won't work for me though

var rocks : int = 0;var rocksToWin : int = 8;var distanceToRock : float = 4;var ray = Camera.main.ScreenPointToRay(Vector3(Screen.width * 0.5, Screen.height * 0.5, 0));var hit : RaycastHit;function Start () {	Screen.lockCursor = true;}function Update(){	if(Input.GetKeyDown(KeyCode.E))		if(Physics.Raycast(ray, hit, distanceToRock))		if(hit.collider.gameObject.tag == "rock")			rocks += 1;			Debug.Log("a rock was picked up. Total rocks =" + rocks);			}					if(rocks >= rocksToWin);{		Application.loadLevel(0);		}
Link to comment
Share on other sites

Link to post
Share on other sites

Still seems like you're a bit confused on the brackets.

function Update(){ // open bracket 1    if(Input.GetKeyDown(KeyCode.E))        if(Physics.Raycast(ray, hit, distanceToRock))        if(hit.collider.gameObject.tag == "rock")	    rocks += 1;	    Debug.Log("a rock was picked up. Total rocks =" + rocks);	    } // closing bracket 1 (is actually closing the function here)	    if(rocks >= rocksToWin);{ // opening bracket 2 (this isn't actually in the function "Update" any more. Also a semicolon shouldn't be here)        Application.loadLevel(0);    } // closing bracket 2

I recommend you use brackets for every if statement since you're having the trouble figuring out where everything is going. Like this

function Update(){ // open bracket 1    if(Input.GetKeyDown(KeyCode.E)) { // opening bracket 2        if(Physics.Raycast(ray, hit, distanceToRock)) { // opening bracket 3            if(hit.collider.gameObject.tag == "rock") { // opening bracket 4	        rocks += 1;	        Debug.Log("a rock was picked up. Total rocks =" + rocks);	    } // closing bracket 4        } // closing bracket 3     } // closing bracket 2	    if(rocks >= rocksToWin) { // opening bracket 5        Application.loadLevel(0);    } // closing bracket 5} // closing bracket 1
Link to comment
Share on other sites

Link to post
Share on other sites

 

I recommend you use brackets for every if statement since you're having the trouble figuring out where everything is going.

Did what you said, Instead of spamming "a rock was picked up. Total rocks = 0" nothing happens at all, all of the objects are labeled 'rock' but none of the code is working except for the screen lock.

Link to comment
Share on other sites

Link to post
Share on other sites

This code

rocks += 1;Debug.Log("a rock was picked up. Total rocks =" + rocks);

is inside multiple nested if statements. If it's not being executed, it's because the if statements aren't all evaluating the conditions to true.

 

That code will only run if 

Input.GetKeyDown(KeyCode.E) // is true// ANDPhysics.Raycast(ray, hit, distanceToRock) // is true// ANDhit.collider.gameObject.tag == "rock" // is true
Link to comment
Share on other sites

Link to post
Share on other sites

It don't quite see how this is a problem.

If you are comparing different datatypes or undefined variables, then it's your fault as a programmer do not take care of it and not the one of JS.

and no imho a and b should not be the same when you give a little about OO.

1st of all, Truthy/Falsy conditions are not consistent : this can easily confuse new programmers.

2nd of all, Javascript is much more FOO then OOP.  Meaning things like NULL == UNDIFINED and 0 == ''" can really mess with you.

3nd of all, Javascript is dynamically typed. So non-strict conditions is a HUGE code smell. 

 

You can't unit test well with ==, you cant use higher order functions that have "Knowgood" swaps, and many other things like THIS.

var c = { x: 1, y: 2 };var d = { x: 1, y: 2 };c == d            // false : In most Foo Langs, this would be truec === d           // false 

Long story short, in JS your go to equals operator should be ===

Link to comment
Share on other sites

Link to post
Share on other sites

Did what you said, Instead of spamming "a rock was picked up. Total rocks = 0" nothing happens at all, all of the objects are labeled 'rock' but none of the code is working except for the screen lock.

Could you maybe post a video of what the game consists of? Knowing some context would be much more helpful.

Link to comment
Share on other sites

Link to post
Share on other sites

Could you maybe post a video of what the game consists of? Knowing some context would be much more helpful.

Sorry, I really can't, It's in a highschool class. but It is basically just 'Slender' but with rocks instead of pages.

Link to comment
Share on other sites

Link to post
Share on other sites

Sorry, I really can't, It's in a highschool class. but It is basically just 'Slender' but with rocks instead of pages.

So is this a first-person 3D game? Do you have a player capsule that moves about?

Link to comment
Share on other sites

Link to post
Share on other sites

I'm assuming he's not making a fully fledged game, but rather he's taking the Slender source code and simply changing the rocks to pages. He's not doing this from scratch since he already has the source, so the capsule, among other features and models, is most likely already present.

Hmmm well I am at a loss then. I was able to build something similar and have it working but it was far more complicated than what he was trying to do. With like 4 different scripts.

Link to comment
Share on other sites

Link to post
Share on other sites

So is this a first-person 3D game? Do you have a player capsule that moves about?

The game is literally the exact game as slender just with rocks. There is the First person controller and capsule thing.

Link to comment
Share on other sites

Link to post
Share on other sites

The game is literally the exact game as slender just with rocks. There is the First person controller and capsule thing.

Well I made it work with my own setup and script however I don't think you'd be able to apply it to your project properly.

Link to comment
Share on other sites

Link to post
Share on other sites

Well I made it work with my own setup and script however I don't think you'd be able to apply it to your project properly.

Why is that?(hope I don't sound snotty, I just want to get a decent grade on this project ;-;)

Link to comment
Share on other sites

Link to post
Share on other sites

Why is that?(hope I don't sound snotty, I just want to get a decent grade on this project ;- ;)

I used completely different scripting and used a directional light as the score keeper (what keeps track of the rocks you pick up) basically. I don't know if it would work but I could post it anyways.

 

This is the rock script: (Applied to the rock objects.)

var cameraObject : GameObject;var message : String = "A Rock was picked up. Total Rocks = ";var scoreKeeper : GameObject;function Update () {	if(scoreKeeper.GetComponent(ScoreKeepingScript).displayTime <= 0.0f)	{		Destroy(gameObject);	}}function OnMouseOver (){	if(Input.GetKeyDown(KeyCode.E))	{		scoreKeeper.GetComponent(ScoreKeepingScript).displayMessage = true;		scoreKeeper.GetComponent(ScoreKeepingScript).rocks += 1;	}} 

This is the ScoreKeeper Script, it uses an Empty Game Object to handle counting the rocks and counting them up to when you win. If you want the Message to display for a shorter period of time you'll need to change the displayTime variable:

var rocks : int = 0;var displayMessage : boolean = false;var displayTime : float = 5.0f;var message : String =  "A Rock has been picked up. Total Rocks = ";var rocksToWin : int = 8;function Update () {	if(displayMessage)	displayTime -= Time.deltaTime;		if(displayTime <= 0.0)	{		displayMessage = false;	}		if(rocks == rocksToWin)	{		Application.LoadLevel(0);	}}function OnGUI (){	if(displayMessage)	{		GUI.Label(new Rect(Screen.width / 2, Screen.height / 2, 200f, 200f), (message + rocks));	}}
Link to comment
Share on other sites

Link to post
Share on other sites

 

I used completely different scripting and used a directional light as the score keeper (what keeps track of the rocks you pick up) basically. I don't know if it would work but I could post it anyways.

 

That worked out very well, but it deletes all of the rocks instead of just the one I picked up. Anyway I could go about fixing this?

Link to comment
Share on other sites

Link to post
Share on other sites

That worked out very well, but it deletes all of the rocks instead of just the one I picked up. Anyway I could go about fixing this?

Hmmm you could try numbering the rocks like Rock1 Rock2 etc. And in the rock script changing "Destroy(gameObject)" change it to "Destroy(RockX)" and on each rock replace the "X" with the corresponding number.
Link to comment
Share on other sites

Link to post
Share on other sites

Hmmm you could try numbering the rocks like Rock1 Rock2 etc. And in the rock script changing "Destroy(gameObject)" change it to "Destroy(RockX)" and on each rock replace the "X" with the corresponding number.

I'll give that a try when I get to class tomorrow

Link to comment
Share on other sites

Link to post
Share on other sites

I fiddled with my code a bit and then some error started happening which wasn't happening before, the error is "Assets/rockScript1.js(9,24): BCE0023: No appropriate version of 'UnityEngine.Object.Destroy' for the argument list '(System.Type)' was found." I changed my script to the script below to try something and now I have no idea what to do.

Edit: Accidentally made a capital 'G' on gameObject, the error is fixed now. Script changed to fit the new one

Edit2: Nothing I've tried worked, it either deleted all of the objects or none of them. I'm probably over looking one method though.

var cameraObject : GameObject;var message : String = "A Rock was picked up. Total Rocks = ";var scoreKeeper : GameObject; function Update () {	if(scoreKeeper.GetComponent(ScoreKeepingScript).displayTime <= 0.0f)	{		Destroy(gameObject);	}} function OnMouseOver (){	if(Input.GetKeyDown(KeyCode.E))	{		scoreKeeper.GetComponent(ScoreKeepingScript).displayMessage = true;		scoreKeeper.GetComponent(ScoreKeepingScript).rocks += 1;	}} 
Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×