C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ClassesClasses are the blueprints for your objects. Basically, in Unity, all of your scripts will begin with a class declaration. Unity automatically puts this in the script for you when you create a new C# script. This class shares the name as the script file that it is in. This is very important because if you change the name of one, you need to change the name of the other. So, try to name your script sensibly when you create it. The class is a container for variables and functions and provides, among other things. Class is a nice way to group things that work together. They are an organizational tool, something known as object-oriented programming or OOP for short. One of the principles of object-oriented programming is to split your scripts up into multiple scripts, each one taking a single role or responsibility classes should, therefore, be dedicated ideally to one task. The main aim of object-oriented programming is to allow the programmer to develop software in modules. This is accomplished through objects. Objects contain data, like integers or lists, and functions, which are usually called methods. ExamplePlayer.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player { public string name; public int score; public int speed; public void gameData() { Debug.Log("Player name = " + name); Debug.Log("Player power = " + score); Debug.Log("Player speed = " + speed); } } PlayerDetails.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerDetails : MonoBehaviour { private Player P1; private Player P2; private Player P3; void Start() { P1 = new Player(); P2 = new Player(); P3 = new Player(); P1.name = "Bill"; P1.score = 10; P1.speed = 30; P2.name = "Bob"; P2.score = 100; P2.speed = 3; P3.name = "Jerry"; P3.score = 50; P3.speed = 10; P1.gameData(); P2.gameData(); P3.gameData(); } } Output: Attach the PlayerDetails.cs script file to the GameOject's component and play the game. It will display the following output:
Next TopicArrays
|