- Home /
Problem using 'function Update ()' to restart the game, error CS0246
This is my script:
using UnityEngine; using System.Collections;
public class Score : MonoBehaviour {
public GUISkin ScoreSkin;
int playerScore = 0;
int enemyScore = 0;
public void IncreaseScore (int PlayerType) {
if (PlayerType == 1) {
playerScore++;
}
else if (PlayerType == 2) {
enemyScore++;
}
}
void OnGUI() {
if (GUI.skin != ScoreSkin) {
GUI.skin = ScoreSkin;
}
GUI.Label (new Rect (20, 10, 300, 30), "Player Score: " + playerScore.ToString ());
GUI.Label (new Rect (20, 35, 300, 30), "Enemy Score: " + enemyScore.ToString ());
}
function Update () {
if (Input.GetKeyDown (KeyCode.Return)) {
Application.LoadLevel (0);
}
}
}
I'm trying to use 'function Update ()' to restart the game (it's a simple Pong game) but Unity gives me this error.
I've never programmed before in my life so I have no idea what to do, I've followed tutorials up until this point to make the game. It seems to work fine using 'void Update ()' instead, but that's probably not right, not that I know why.
Can anyone explain what I did wrong, why it's wrong, and how to fix it?
Ty, from a noob.
Answer by ejpaari · Apr 09, 2014 at 10:05 AM
Use void Update()
in C# because methods require a return value and function
is not a known type. function Update()
is used in Javascript. I would also suggest doing yourself a favor and learning some programming first.
Answer by HarshadK · Apr 09, 2014 at 10:22 AM
As you said you are a noob, to start with let me tell you that there are multiple languages available to script in for Unity. These languages are c#, Javascript (UnityScript), and Boo.
You can program for Unity using any of these languages but when you write a script it is mandatory to write the whole script in only one language out of these three.
Now in relation to the error you are facing, you have written your script in c#. In C# you specify return type before a function name when declaring them. As you have done here with your 'IncreaseScore' function. You specified its return type as 'void'. When you declare functions in Jaavascript, you prepend it with word 'function' to let Unity compiler know it is a function.
As you are writing your script in c# you can not use keyword 'function' to specify that it is a function as it is not required in c#. That's why specifying 'void' before Update works in your script and not 'function'.
Its like you are trying to put your shoes in your fridge. That's why there is shoe rack for it, my friend!
And before you dive into coding directly, I suggest you to read this section for Unity Scripting and watch these videos for Unity Scripting Tutorials.
Your answer
Follow this Question
Related Questions
Incremental game need help 1 Answer
Main Menu Script Issues 1 Answer
Reflections error please help!!! 1 Answer
How do I close my game using the escape key? 2 Answers
Unity Game Not Launching. 0 Answers