Script Basics in Unity

 


I met Unity about 5 months ago thanks to a Game Academy. Before that, I had no purpose and interest in writing games.

Thanks to the academy I was accepted by chance, I started to work on games and to tell a lie, I liked it. Since I have a C# foundation, I started the subject with some self-confidence, but I learned with bitter experience that what I know in software is a camel’s ear compared to what I don’t know, because this C# was not the C# I knew 😛

Fortunately, I adapted quickly and developed small game projects as the academy progressed. At the end of the 3-month period, I submitted my graduation project. If I get accepted and graduate from the programme, I will announce it here.

Let’s talk about Unity.

What is Unity?

We can define Unity as a game engine that facilitates and accelerates the game development process. Thanks to the toolkits it contains, we can design 2D and 3D games.

It has a very large community and even its own training page called UnityLearn if we know English, and I think it is very useful and comprehensive for learning simple developments.

Using Unity, we can develop games to be played on different platforms such as computers, mobile devices and game consoles.

There is an Asset Store where ready-made assets, models, sounds can be downloaded with paid and free options. From here, we can download assets such as simple objects or characters and use them directly in our project.

Scripting

Let’s come to Scripting, which is the main subject of my article. In Unity, we can move game objects, add interactions, create game mechanics and many other things with the scripts we write, that is, with code files.

It is ideal to create a folder named Scripts under the project folders and collect all the Script files we will write in this folder. We can do this by right clicking on the project folders with the Create Folder option.

In the screenshot above we can see the folders of a game I developed. I have downloaded two different asset folders from AssetStore and these are also visible among the project folders. The Script folder I created with the Create command comes with an empty icon because there is no file in it yet. When I go into this folder and select the Create C# Script command, an image like the one below appears.

This is my new Script file. When I double-click on it, I get a window with the Script file created using Visual Studio, which is what we install when we install Unity on our computer. And here is my Script file:

This file comes with a class name. This class is the same as our file name. In this example I did not delete the default name, so it came with the name NewBehaviourScript. However, we make our own naming in the development environment: PlayerController, BallController, SpawnManager, etc.

The Start and Update methods that appear in the class come ready. We can write our code into these methods if necessary, or if not needed, we can delete them and create our own methods.

Script Content

We write our scripts in C# language and control the behaviour and interaction of game objects. For example, we can use functions provided by Unity such as transform.Translate to move an object or event methods such as OnCollisionEnterOnTriggerEnter to interact with other objects.

Let’s write a script to move our player horizontally and vertically.

Here we determine the movement speed of the player we want to move at the beginning.

Then we start writing our codes in the Update method that runs once in each frame.

Input.GetAxis("Horizontal"): We get the horizontal (left-right) input from the keyboard.

Input.GetAxis("Vertical"): We get vertical (forward-backward) input from the keyboard.

Vector3 moveDirection: We create a vector to determine the direction of movement. We fix the length of the vector to 1 by normalising it. This means converting the length of the vector to 1 while maintaining its direction. We do this especially in cases where the size (length) of the vector can take different values, because this way the direction of the vector becomes important, not its size.

transform.Translate(moveDirection * moveSpeed * Time.deltaTime): With this line, we can move the player using the specified move direction and speed. Time.deltaTime represents the time elapsed in each frame depending on the performance of the game and thus ensures that the movement is smooth and realistic.

We wrote our codes to move the actor, and we put our actor on our stage. So how does the program understand that these codes should move the actor? We do this as follows: By clicking Add Component in the Inspector section of the player character we have determined or by dragging the script to the Inspector section, we connect it to our player.

As we can see above, the variables and other information in the Script have been added to our Player. Here, since we set the moveSpeed variable as public, it appeared here with the assigned value of 5 and we can change this 5 value up or down if we want. If we had defined this variable as private, it would not appear here and therefore could not be changed.

It remains to test whether the codes we have written work correctly. We can do this by running the game, that is, by pressing play. If it does not work, we need to go back to the codes we wrote and check whether we have connected the Script to the correct component.

There is another important thing we need to know at this point. We pressed play to test the script and ran the game. From the example above, we made the moveSpeed variable 10 instead of 5. Of course, we can control what and how the change we made affects what we do, of course, this feature is already there for this. However, after running the game, that is, when we are in Play mode, any changes we make are not saved. So when we stop the game, we see that the variable is set back to 5. Let’s pay attention to this too.

As a result, Script programming has a fundamental role in the game development process in Unity. By controlling the behaviour and interaction of game objects, we can create the game mechanics we want. I hope it was useful.

Thanks for reading.

Selin.

Unity’de Script Temelleri

 


Unity ile bir Oyun Akademisi programı sayesinde yaklaşık 5 ay önce tanıştım. Onun öncesinde oyun yazmak gibi bir amacım ve ilgim yoktu.

Tesadüfen kabul edildiğim bir program sayesinde oyun üzerine çalışmalar yapmaya başladım ve ne yalan söyleyeyim hoşuma gitti. C# temelim olduğu için konuya biraz özgüvenle giriştim ancak yazılımda bildiklerimin bilmediklerim yanında devede kulak olduğunu acı tecrübeyle öğrendim zira bu C# benim bildiğim C# değildi 😛

Çabuk adapte oldum neyse ki ve program ilerledikçe ufak da olsa oyun projeleri geliştirdim. 3 aylık sürecin sonunda bitirme projemi de teslim ettim. Eğer kabul alırsam ve programdan mezun olabilirsem onu da buradan duyuracağım.

Gelelim Unity’ye.

Unity Nedir?

Unity’yi oyun geliştirme sürecini kolaylaştıran ve hızlandıran bir oyun motoru olarak tanımlayabiliriz. Bünyesinde barındırdığı araç setleri sayesinde 2D ve 3D oyunlar tasarlayabiliyoruz.

Çok geniş bir topluluğu ve hatta İngilizce biliyorsak UnityLearn adında kendi eğitim sayfası bile var ve bence basit geliştirmeleri öğrenmek için oldukça faydalı ve kapsamlı.

Unity’yi kullanarak bilgisayarlar, mobil cihazlar ve oyun konsolları gibi farklı platformlarda oynanmak üzere oyunlar geliştirebiliyoruz.

Hazır varlıkların, modellerin, seslerin ücretli ve ücretsiz seçenekleriyle indirilebileceği bir Asset Store’u var. Buradan basit nesneler ya da karakterler gibi varlıkları indirerek projemizde direkt olarak kullanabiliyoruz.

Scripting

Yazımın esas konusu olan Scripting’e gelelim. Unity’de oyun nesnelerini hareket ettirme, etkileşimler ekleme, oyun mekaniği oluşturma ve daha pek çok şeyi yazdığımız Script’ler ile yani kod dosyaları ile gerçekleştirebiliyoruz.

Proje klasörleri altında Scripts isimli klasör oluşturarak tüm yazacağımız Script dosyalarını bu klasörde toplamak ideal olanı. Bunu da proje klasörlerine sağ tıklayarak Create Folder seçeneği ile yapabiliriz.



Yukarıdaki ekran görüntüsünde benim geliştirdiğim bir oyunun klasörlerini görebiliriz. İki farklı asset klasörünü AssetStore’dan indirdim ve bunlar da proje klasörleri arasında görünüyor. Create komutu ile oluşturduğum Script klasörü henüz içerisinde bir dosya bulunmadığından içi boş ikonla geliyor. Bu klasörün içerisine girip Create C# Script komutunu seçtiğimde ise aşağıdaki gibi bir görüntü oluşuyor.

Bu benim yeni Script dosyam. Buna çift tıkladığımda karşıma Script dosyasının Visual Studio programı kullanarak oluşturulmuş penceresi geliyor ki Unity’yi bilgisayarımıza kurarken bu programı da beraberinde kuruyoruz. Ve işte Script dosyam:

Bu dosya bir sınıf adıyla geliyor. Bu sınıf dosya adımızın aynısı. Buradaki örnekte ben default tanımlanan ismi silmedim, bu yüzden NewBehaviourScript adıyla geldi. Ancak geliştirme ortamında kendimiz isimlendirme yapıyoruz: PlayerController, BallController, SpawnManager gibi.

Sınıf içerisinde görünen Start ve Update metotları hazır geliyor. Kodlarımızı gerekirse bu metotların içerisine yazabilir ya da gerekmiyorsa bunları silip kendi metotlarımızı da oluşturabiliriz.

Script İçeriği

Script içerisine kodlarımızı C# dilinde yazıyoruz ve oyun nesnelerinin davranışlarını ve etkileşimlerini kontrol ediyoruz. Örneğin, bir nesneyi hareket ettirmek için transform.Translate gibi Unity'nin sağladığı fonksiyonları ya da diğer nesnelerle etkileşim kurmak için OnCollisionEnterOnTriggerEnter gibi olay yöntemlerini kullanabiliyoruz.

Oyuncumuzu yatay ve dikey eksende hareket ettirecek Scripti yazalım.



Burada başlangıçta hareket etmesini istediğimiz oyuncumuzun hareket hızını belirliyoruz.

Sonrasında her karede bir kez çalışan Update metodu içerisine kodlarımızı yazmaya başlıyoruz.

Input.GetAxis("Horizontal"): Klavyeden alınan yatay (sol-sağ) girişi alıyoruz.

Input.GetAxis("Vertical"): Klavyeden alınan dikey (ileri-geri) girişi alıyoruz.

Vector3 moveDirection: Hareket yönünü belirlemek için bir vektör oluşturuyoruz. Normalize ederek vektörün uzunluğunu 1'e sabitliyoruz. Bu, vektörün yönünü korurken uzunluğunu 1'e dönüştürmek anlamına geliyor. Bunu özellikle vektörün büyüklüğünün (uzunluğunun) farklı değerler alabileceği durumlarda yapıyoruz, çünkü bu şekilde vektörün yönü önemli hale geliyor, büyüklüğü değil.

transform.Translate(moveDirection * moveSpeed * Time.deltaTime): Bu satırla oyuncuyu, belirlediğimiz hareket yönü ve hızı kullanarak hareket ettirebiliyoruz. Time.deltaTime, oyunun performansına bağlı olarak her karede geçen süreyi temsil ediyor ve bu sayede hareketin pürüzsüz ve gerçekçi olmasını sağlıyor.

Oyuncuyu hareket ettirecek kodlarımızı yazdık. Oyuncumuzu da sahnemize koyduk. Peki bu kodların oyuncuyu hareket ettirmesi gerektiğini program nasıl anlar? Bunu da şu şekilde yapıyoruz: Belirlediğimiz oyuncu karakterin Inspector bölümünde Add Componenta tıklayarak ya da Scripti Inspector bölümüne sürükleyerek oyuncumuza bağlıyoruz.


Yukarıda gördüğümüz gibi Script içerisinde bulunan değişkenler ve diğer bilgiler ile Oyuncumuza eklendi. Burada moveSpeed değişkenini public olarak belirlediğimiz için atanan 5 değeri ile birlikte burada göründü ve istersek bu 5 değerini aşağı ya da yukarı yönlü değiştirebiliyoruz. Eğer bu değişkeni private olarak tanımlamış olsaydık burada görünmeyecek dolayısıyla değiştirilemeyecekti.

Geriye yazdığımız kodların doğru çalışıp çalışmadığını test etmek kalıyor. Bunu da oyunu çalıştırarak yani play’e basarak yapabiliyoruz. Eğer çalışmıyorsa yazdığımız kodlara dönüp kontrol etmemiz ve Script’i doğru bileşene bağlayıp bağlamadığımızı kontrol etmemiz gerekiyor.

Bu noktada bilmemiz gereken önemli bir şey daha var. O da şu: Script’i test etmek amaçlı play’e bastık ve oyunu çalıştırdık. Yukarıdaki örnekten gidersek moveSpeed değişkenini 5 yerine 10 yaptık. Yaptığımız değişikliğin neleri nasıl etkilediğini kontrol edebiliyoruz elbette ki bu özellik zaten bunun için var. Ancak oyunu çalıştırdıktan sonra yani Play mode’da iken yaptığımız hiçbir değişiklik kaydedilmiyor. Yani oyunu durdurduğumuzda değişkenin 5 değerine geri çekildiğini görüyoruz. Buna da dikkat edelim.

Sonuç olarak Script programlama, Unity’de oyun geliştirme sürecinde temel bir role sahip. Oyun nesnelerinin davranışlarını ve etkileşimlerini kontrol ederek, istediğimiz oyun mekaniğini oluşturabiliyoruz. Umarım faydalı olmuştur.

Teşekkürler.

Selin.