Creating a new C# script in Unity is similar to our approach for creating scripts using JavaScript or any of the other scripting languages.
NewBehaviorScript
with some stubs for the methods Start()
and Update()
:Scripts
and then drag the newly created script into the Scripts directory. A best practice for scripts is to put them in a folder in the project. What you call this folder doesn't really matter, as it is more for your own organizational purposes than it is for Unity. You may choose to put UI centric scripts in one directory and AI scripts in another. However you manage the scripts is up to you, but you will create a large number of scripts in the course of creating the average game so you want to organize them so that they aren't all sitting at the root of your game project.
As mentioned earlier, you can add a script to a GameObject by simply dragging the script onto the game object itself. What is important here, is that the GameObject is the owner of the script, if that game object is not participating in the scene – the methods in the script will never be called. For scripts that are global in nature, a common practice is to create an Empty Game Object in the scene and attach the global scripts to it. While it is common for people to associate these global scripts with the camera, you want to avoid this as many complex games will have many cameras – complicating the activation of the scripts as well as determining which object in the scene owns them.
Quite often you will find yourself in the position of having written a script providing some values for variables within your script. As you test your game you will find that you will want to expose some of these variables to the Unity Editor so that you can modify them in the editor without having to edit and recompile the scripts themselves.
This is particularly important since many times you will want to provide a default value within the script which you can override due to some specific game use case. Rather than coming up with some complex mechanism to do this, simply declare the variable as a public variable and it will show up in the Unity editor.
Scripting inside Unity consists of attaching custom script objects called behaviors to game objects. Different functions inside the script objects are called on certain events. The most used ones being the following:
3.133.109.211