- Home /
Learning C# instead of doing what tutorials say...
Hi! The tutorials here are great, but I'm having troubles when trying to make my own scripts. I think its a problem with knowing what I want to do, and how to translate that into C#.
Example Code:
using UnityEngine;
using System.Collections;
public class ExampleBehaviourScript : MonoBehaviour
{
void Update ()
{
if(Input.GetKeyDown(KeyCode.R))
{
gameObject.renderer.material.color = Color.red;
}
if(Input.GetKeyDown(KeyCode.G))
{
gameObject.renderer.material.color = Color.green;
}
if(Input.GetKeyDown(KeyCode.B))
{
gameObject.renderer.material.color = Color.blue;
}
}
}
This script is from Scripts as Behavior Components. In a nutshell, they wanted to make the box change color if certain buttons are pressed. Here are a few questions I've had regarding scripting. What is the significance of the void and () in void Update (){}? The if statements are methods, which is why they require {} brackets around their properties (is that the word I'm looking for?)? And is the statement gameObject.renderer.material.color kind of like an address of what we are interested in changing? Also, if you can point me to some good material on learning the terminology and basics in unity C#. I've found stuff for C# in other scopes, but it seems different from unity for some reason; like there is no main () function :(. Thanks for all your help!
A very generous answer from Vexe. Raine, normally this site is for Unity specifically. if you go to "stack overflow" or whatever it's called you can always get beaucoup help on general program$$anonymous$$g. Cheers
You can always use Unity without writing code, if you get a visual scripting tool like Playmaker:
https://www.assetstore.unity3d.com/#/content/368
Or you can read a book to learn both about Unity and scripting. For example:
Answer by vexe · Oct 12, 2013 at 06:21 AM
In programming, there's something called a function
- a function is like a box, it has input and output. Inside that box, there are some operations going on for you to get the output from your input. Just like in math, for example:
F(x) = x^2 + 1;
This is a function, it takes an x
as an input, and gives you an output of the result of the operation x^2 + 1
Functions in programming are no different, but you have to be more specific, you have to specify the input and output data types. The general syntax of a function (In C/C++/C#):
RETURN_TYPE FUNCTION_NAME(TYPE_0 INPUT_PARAM_0, TYPE_1 INPUT_PARAM_1, ..., TYPE_N INPUT_PARAM_N)
{
// function body
}
Now, in my previous simple math example:
RETURN_TYPE
is fromR
(Real numbers)FUNCTION_NAME
isF
TYPE_0
is also fromR
(input is all the real numbers, you could pass in anything)INPUT_PARAM_0
isx
(only one input parameter)The
=
sign signifies the beginning of the function's body.
Let's convert that math function to its equivalent programming one:
float F(float x)
{
return x ^ x;
}
The return type is
float
which includes everything from decimal to whole numbers (R) (You could also usedouble
for that matter,double
gives you more accuracy but takes more memory thanfloat
)Function name is
F
One input parameter
x
of typefloat
(belongs to R)In the function body,
x
gets squared, and the square gets returned (this is the output)The
{
here, signifies the beginning of the function's body, and}
signifies the end. In other words the body must go between the{ }
that's why you need them.Just like in math, a function returns only
one
value (if it has a return type other than void), and it could accept more than one input parameter.
The return
keyword does 2 things:
Exits out the function.
Returns what's after it to the caller, (in our case we're returning
x^x
)
Now, how can we use this function?
float result = F(5);
print (result); // 25
Simple enough huh?
But notice something, your variable type must match with what the return type of your function, so you can't do:
string result = F(5);
string = float?? wtf??
There are a couple of exceptions to this:
The return type is stronger than your variable's type:
int result = F(1.5f); print (result); // 2 - and not 2.25! When you assign int = float, what's after the decimal gets truncated
The return type is weaker than your variable's type:
double result = F(1.5f); print (result); // 2.25 - that's OK. See [this][1], for more info
Polymorphism and inheritance:
Enemy e = new Zombie(); // Assuming `Zombie` inherits from `Enemy` => a `Zombie` "is a" `Enemy` so the types match with each other
Now, recall that in math, you can't call something a function
unless it returns a value. In programming can have functions, that returns nothing (VOID) (no output) - Sometimes they're called Side effects
cause they give you no output, but still do something to make something happen. You can also have functions that take no arguments (no input)
How can you create these sorta functions? - you use, the void
keyword, which means nothing
void DoSomething()
{
// ...
}
Now DoSomething
takes no input, and has no output! And since you specified the return type to be void
you can't tell it to give you something back (cause with void
you told it I don't need anything from you) - So statements like return SOME_VALUE;
is invalid.
But notice, remember the 2 tasks of return
? it exits and return what's after it. Which means, we could still use it to exit out the function:
void DoSomething()
{
if (certainThingHappen)
return;
// all the code after this point, won't be executed cause we can't reach it anymore
// since we exited out
}
This is the case with the Update
method in Unity, it returns and takes nothing.
You might wanna ask, what's the difference between a function, and a method? Practically speaking, nothing. Technically speaking, if a function
is sitting inside a class, it's called a method
. Now you might say, how in the world would a function, live outside a class? - Well, that's how procedural
programming languages used to deal with stuff, like C for example. There's no classes there. So you write your functions in the global space.
Can you interchangeably use the two names? - Yes. But methods would be more accurate in the case of OOP languages such as C#
Now:
The if statements are methods, which is why they require {} brackets around their properties (is that the word I'm looking for?)
From what I just told you, you should know that your statement is inaccurate. The if
is a programming keyword, it takes a boolean statement
as its input, if that statement returned true, the body gets executed, otherwise not.
What's a boolean statement? Anything that could return a true or false. In discrete math, it's called a proposition
For example:
1 > 2 // This statement return `false` cause 1 is less than 2
you are a tall guy // If you're tall, then it's true otherwise false
A practical example:
Player.cs
public bool isDead = false;
void InflictDamage(int amount)
{
hp -= amount;
isDead = hp <= 0;
}
GameController.cs
void Update()
{
if (Player.isDead)
GameOver();
}
Notice I didn't put { }
around the if
's body, that's cause it's only one statement, if you have more, only then you'll need them.
First, what's a bool? It's a variable that could hold either true/false, which means it's very handy for our conditional statements. A bool takes 1 byte of memory.
Second, you might have had trouble with the statement isDead = hp <= 0;
It's simple, isDead
is a boolean, hold true or false. hp <= 0
is a boolean expression (a proposition) it could either return true or false. If the health points are less than or equal to 0, than the expression is true, so isDead = true;
otherwise isDead = false;
Third, in our GameController
's Update method, we're checking to see if the player is dead or not, if so we end the game with a call to GameOver()
A lot of new-comers do the redundant: if (Player.isDead == true)
- with the knowledge you have right now, you should know why this is redundant :-)
In your case, Input.GetKeyDown(key)
is a static
function that returns true in the frame that key
was pressed in, false afterwards. See this for more info.
Lastly, for some learning materials, I suggest you improve your programming skills in general and then come back to Unity and C# (Please forget about JS, it hides a lot of stuff from you). I'd recommend a low level language like C++. Just get the concepts from it, then move on to OOP and higher level languages like C#. Why C++ and not C# right away? Cause from the looks of it, you're a new-comer to programming, as well as Unity. Starting programming with a high-level language isn't quite efficient. You'll get distracted by things like class
, static
, etc. Get the basics first, learn procedural programming and then object oriented programming. Also, work on solving programming problems in general. Check out this simple series I made on C++, it's nice simple with tons of problems with various difficulties. (The series not complete yet unfortunately, I only went over the basics) - But it should help you understand things better. (Never let anyone scare you away from C++, it's very simple)
Also, as @MrProfessorTroll said, thenewboston is an amazing source to learn from!
The problem with Unity tutorials, is that they never really teach you how to think
, they just tell how to do this and that, with more focus on the WOW
side more than the HOW
. But for nicely explained tutorials, I'd recommend Quil18creates channel (check out the brick game, and the FPS), and the UnityGems guys (kinda advanced) - Also, UnityOfficials is good.
Good luck!
[1]: http://answers.unity3d.com/questions/537226/problem-with-displaying-the-countdown-timer.html#comment-550050
Oh wow. This answer is going to take all weekend to digest. Thank you very much!
Answer by MrProfessorTroll · Oct 12, 2013 at 05:50 AM
A function needs parameters. So the () is necessary. Void means that there is no return type. Honestly, if these are things that you don't know, you should just learn to program first and not jump straight into game development. It wont get you far. Here learn this: http://thenewboston.org/list.php?cat=16
If you know C++, you have a basic knowledge of every language, since most programming languages are very very very similiar. Please watch them all and them come back here, as it is a million times easier to do now. Good luck!!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Unexpected Symbol 'end-of-file' C# Error CS8025 1 Answer
Serialized variables not sharing 2 Answers