C# / C# Game Development with Unity

Scripting with C# in Unity

This tutorial will introduce you to scripting in C# within Unity. You'll learn how to create scripts, attach them to game objects, and control game object behavior through scripti…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Introduces game development using Unity and C# to build interactive games.

Introduction

This tutorial aims to provide a comprehensive understanding of scripting in C# within the Unity engine. By the end of this tutorial, you will learn how to create scripts, attach them to game objects, and manipulate these game objects using scripts.

Prerequisites: Basic knowledge of C# programming and Unity interface would be helpful.


Step-by-Step Guide

Scripts in Unity are written in C# and are used to create and control game behavior. To create a script:

  1. Right-click on the Project window and select Create > C# Script. Name the script and press Enter.

  2. Unity will automatically open the script in a code editor (like Visual Studio). The script will contain a template with two methods: Start() and Update().

  3. Start() is called before the first frame update. It's a good place for initialization code.

  4. Update() is called once per frame. It's often used for moving game objects, reading input, etc.

To attach a script:

  1. Select the game object in the Scene or Hierarchy window.
  2. In the Inspector window, click Add Component and select the script.

Code Examples

Example 1: Moving a game object

using UnityEngine;

public class MoveObject : MonoBehaviour
{
    public float speed = 10.0f; // Declare a public float for speed. 

    // Update is called once per frame
    void Update()
    {
        // Move the game object in a straight line at a constant speed.
        transform.Translate(speed * Time.deltaTime, 0, 0);
    }
}

This script will move a game object in a straight line at a constant speed. transform.Translate() moves the object in the direction and distance of translation. Time.deltaTime is used to make movement smooth and frame rate independent.

Example 2: Rotating a game object

using UnityEngine;

public class RotateObject : MonoBehaviour
{
    public float rotationSpeed = 100.0f; // Declare a public float for rotation speed.

    // Update is called once per frame
    void Update()
    {
        // Rotate the game object around the y-axis at a constant speed.
        transform.Rotate(0, rotationSpeed * Time.deltaTime, 0);
    }
}

This script will rotate a game object around the y-axis at a constant speed. transform.Rotate() rotates the object around the x, y, and z axes in that order.


Summary

In this tutorial, we've learnt how to create and attach scripts in Unity using C#. We've also explored how to control game object behavior using scripts.

If you want to learn more, try creating complex behaviors by combining different scripts, or explore Unity's Scripting API.


Practice Exercises

  1. Create a script to make a game object move up and down in a sinusoidal pattern.
  2. Create a script to make a game object follow the player's position with a delay.

Exercise 1 Solution:

using UnityEngine;

public class SinusoidalMotion : MonoBehaviour
{
    public float speed = 5.0f;
    public float amplitude = 2.0f;

    private Vector3 startPosition;

    // Start is called before the first frame update
    void Start()
    {
        startPosition = transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = startPosition + amplitude * new Vector3(0, Mathf.Sin(speed * Time.time), 0);
    }
}

This script causes an object to move up and down in a sinusoidal pattern.

Exercise 2 Solution:

using UnityEngine;

public class FollowPlayer : MonoBehaviour
{
    public Transform player;
    public Vector3 offset;
    public float followSpeed = 2.0f;

    // Update is called once per frame
    void Update()
    {
        Vector3 desiredPosition = player.position + offset;
        Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, followSpeed * Time.deltaTime);
        transform.position = smoothedPosition;
    }
}

This script makes an object follow the player's position with a delay.

Remember, the best way to learn is to practice. Try to create more complex behaviors and experiment with different parameters. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Date Difference Calculator

Calculate days between two dates.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help