Unity introductory project - final part. Adding a condition
In the previous section we added a small script to a GameObject that made it move. However it wasn't very controlled and the object just shot off in one direction, never coming back.
We'll make the object bounce back and forward around our position.
To do this we'll check on the current x position of the object. If it's greater than 100 or if it's less than -100 then we'll reverse the direction of movement, simply by changing the movement value from minus to plus (or plus to minus).
We'll make the object bounce back and forward around our position.
To do this we'll check on the current x position of the object. If it's greater than 100 or if it's less than -100 then we'll reverse the direction of movement, simply by changing the movement value from minus to plus (or plus to minus).
If statements in C#
This is the first part of our condition statement. Have a look to see how it works.
A condition begins with the lower case word 'if'. It's then followed by a test, a condition, something that is either true or false. The condition is wrapped in round brackets so that C# knows where it starts and stops. After the condition come the lines that we want to run if the condition is true. Those lines are wrapped in curly brackets (and it's sometimes hard to tell the difference). There can be many lines.
If C# decides that the statement in round brackets is true, then it runs each of the lines between the curly brackets. If it decides that it's false, then it just skips them.
If C# decides that the statement in round brackets is true, then it runs each of the lines between the curly brackets. If it decides that it's false, then it just skips them.
Add the lines so that the code looks like this. Save the changes to the script and switch into Unity. Play the game. You should see the sphere dart off in one direction, then change it's mind and come back.
However it then shoots off to infinity in the other direction. We need to fix that. We won't be very clever about it, just add another opposite condition to check if it's too far the other way. |
Many objects, one script
This is the great thing about Unity. You've created a behaviour script for one rather plain object. However you can attach this script to any other object that you want. Create a new Cube object. Find your script and drag it onto the object. Run the game and both of the objects will start moving in the same way.
Can you ....
- change how far the object move each cycle
- change how fast the object moves each cycle
- change the direction, so that it moves up and down
- make it move in a circle? (need help?)