Thursday, February 18, 2016

Unity 3D reference tutorial

Note to my polish friends: Wiem że poradnik jest po angielsku, ale nie używam trudnych słów i myślę, że każdy sobie z nim poradzi. No w każdym razie jeżeli używacie Unity 3D nie powinniście mieć problemów.

Hi! Today short tutorial about making reference between two scripts in two other gameobjects. I know how frustrating can it be. It's usually announced by Unity error "Object reference not set to an instance of an object". So how to do it right?

Step one:
We have got two scripts: for example we want to change a variable in script called BasicEnemy by the script GameProcessor.

Let's start with creating two scripts named like above. Now (for the example only, i'll show you how to change it later), create two empty gameobjects and name them also BasicEnemy and GameProcessor.
Attach the scripts to the corresponding gameobjects.

Step two: 

Lets start with BasicEnemy script first. Open it and rewrite as at above screen:
Test it. You should get constant message in console "Enemy health is10" because I have "eaten" one space after word "is" ;-) (been a little hungry). Easy, right? Okay now lets go to step three.

Step three:
Go to GameProcessor script. Edit it like on the screenshot below:
For now nothing has changed, yet.

Step four:
Let's do some math! Go again to script GameProcessor and add:
Now, every time you press R key, value of enemyHealth variable will increase by value of multipler variable.

You can also call a function from other script using "reference.ExampleFunction();", what is more you can force a script to do a hard work for another script sending arguments like this "reference.OtherFunction(argument01, argument02);"

I hope I have helped you a little. I know that making reference between scripts is always very hard at the beginning. Goodluck!