ANALYSIS AND OPTIMIZATION OF GRAPHICS PROGRAMMING IN C# USING UNITY
Shoykulov Sh.K.
Senior Lecturer, department of Applied Mathematics, faculty of Computer sciences, Karshi State
university, Karshi, Republic of Uzbekistan https://doi.org/10.5281/zenodo.14000841
Abstract. This review article discusses the Unity framework for C# graphics programming for creating interactive 3D applications and games. An example of practical application of the tool is given and its capabilities and advantages are analyzed. Particular attention is paid to methods for optimizing C# graphics applications in order to improve performance and efficient use of resources. The article also provides a comparative analysis of C# with other programming languages, such as C++, Java, and Python, from the point of view of their use in graphics programming. Key aspects are considered, including performance, ease of development, and their application in various fields. At the end, it is concluded that C# is a universal and powerful tool for developing graphics applications, suitable for both beginners and experienced developers.
Keywords: graphic programming, C#, WPF, GDI+, Unity, 2D graphics, 3D graphics, animation, optimization of graphic applications, game engine, performance, interactive applications, DirectX, OpenGL, cross-platform, visualization, virtual reality, computer graphics, memory management, comparative analysis of programming languages.
Introduction. Graphic programming has come a long way in its evolution, starting with simple drawing systems and reaching modern powerful tools that allow you to create complex visual applications. One of the important stages in the development of this area was the emergence of high-level programming languages, such as C#, which significantly simplified the process of developing graphical interfaces and applications.
C# is actively used for graphical programming due to its integration with technologies such as GDI+ (Graphics Device Interface), WPF (Windows Presentation Foundation) and Unity. These libraries and frameworks offer developers powerful tools for creating 2D and 3D graphics. WPF (Windows Presentation Foundation) is a modern platform designed for developing interactive user interfaces and graphical applications. WPF supports both 2D and 3D graphics, offering more powerful tools compared to GDI+.
In recent years, C# has become widespread in game development due to its integration with the Unity game engine. Unity is a cross-platform engine that is actively used to develop both mobile and desktop applications, games and virtual worlds. Thanks to its tight integration with C#, Unity provides developers not only with tools for working with 3D graphics, but also with the ability to use physics, animation and other key aspects of game mechanics. This makes Unity one of the most popular tools for creating games, especially among indie developers.
When comparing C# with other programming languages such as C++ and Java, it is worth noting that C# has a simpler syntax and high-level functions, which makes the process of developing graphical applications more accessible. Despite this, C# has all the necessary functionality for creating complex graphical solutions with high performance.
C# has proven itself as a powerful tool for graphical programming due to its support for technologies such as GDI+, WPF and Unity. These frameworks allow developers to solve a wide
range of tasks: from creating simple graphical elements to developing complex interactive 3D applications and games. The purpose of this study is to analyze key frameworks for graphics programming in C#, including Unity, and suggest ways to optimize graphics applications for better performance. The introduction explains the relevance of using Unity for developing interactive 3D applications and games.
Results and discussions. Graphics programming is based on several key concepts and theoretical foundations that define how images, shapes, and objects are represented and processed on a computer. These principles include working with raster and vector graphics, using two-dimensional and three-dimensional coordinate systems, and performing mathematical operations such as transformations, scaling, and rendering. Raster and vector graphics are two basic types of graphical representation. Raster graphics are built on a grid of pixels, each of which is assigned a specific color. In C#, working with raster images can be done using libraries such as GDI+, where each pixel is treated individually. Vector graphics, in contrast, are built on mathematical formulas that describe lines, curves, and polygons. Both two-dimensional (2D) and three-dimensional (3D) graphics are important aspects of graphics programming. Technologies such as GDI+ and WPF make it easy to solve problems related to 2D graphics. When working with 3D graphics, you need to consider lighting, textures, perspective, and rendering. Three-dimensional objects are made up of polygons, most often triangles, and their surfaces can be textured or illuminated by various light sources. In C#, using Unity allows you to work with 3D objects, providing tools for creating models, setting up cameras and lights, and creating animations and simulations.[3]
Transformations of graphical objects are an important component of both 2D and 3D graphics. Transformations include operations that change the position, size, or orientation of objects on the screen. The main types of transformations include:
Translation;
Scaling;
Rotation.
In C#, these transformations are implemented using built-in methods and classes, such as RenderTransform in WPF for 2D graphics and through Unity for working with 3D objects. Rendering is the process of displaying a graphical object on the screen. In C#, rendering can be done using either built-in tools like GDI+ or WPF, or specialized frameworks like DirectX or Unity that support complex rendering methods for creating 3D scenes.
Graphics programming in C# is based on fundamental theoretical concepts that provide efficient management of raster and vector images, the use of 2D and 3D coordinate systems, and the implementation of transformations and rendering of objects. Knowing these fundamentals is the key to successful development of graphics applications.
Unity is one of the most popular game engines, widely used for developing 3D and 2D games, interactive applications and simulations. One of the key features of Unity is its integration with the C# programming language, which allows developers to create both simple and complex 3D scenes with physics, animation and interactivity. Unity supports cross-platform development, which allows you to create applications for various devices: from desktop computers to mobile devices and gaming consoles. The main components of 3D graphics in Unity include objects, scenes, cameras, and lights. Each element of the 3D world in Unity is represented as an object, which can be static or dynamic. Objects can consist of simple geometric primitives (cubes, spheres, cylinders) or be complex models created using 3D editors such as Blender or Maya.
Key components that work with 3D graphics in Unity:
Mesh Renderer - a component responsible for displaying a 3D model of an object.
Transform - determines the position, rotation, and scale of an object in 3D space.
Camera - is the "eye" of the player or observer through which the game world is visible. The camera controls how the scene is displayed on the screen.
Light - a light source that illuminates 3D objects. Light sources can be point, directional, or diffuse, which allows you to create realistic shadows and lighting.
To create a 3D application in Unity, you need to start by creating a scene and adding 3D objects to it. Let's look at a simple example of a scene containing a cube that rotates around its axis using C#. After creating a new project in Unity, you can add a 3D object to the scene, such as a cube. Once the object is added, you can create a C# script that will be responsible for rotating the cube. In Unity, scripts are added as components to objects, and the Update method, called every frame, is used to control the behavior of the object. An example of a simple C# script that makes a cube rotate around its axis:
using UnityEngine;
public class RotateObject: MonoBehaviour
{
public float rotationSpeed = 50.0f;
void Update()
{
transform.Rotate(Vector3.up, rotationSpeed * Time.deltaTime);
}
}
Figure 1. 3D graphics created and animated with C# Unity
The script adds a constant rotation speed to the cube. The transform.Rotate command rotates the object by a given angle around the Y axis, and the rotationSpeed variable controls the rotation speed. The Time.deltaTime method provides smooth and continuous time-dependent movement. For this script to work, it must be attached to an object. Once the scene is launched, the cube will begin to rotate around its axis. To create a more realistic 3D scene, it is necessary to add lighting and textures. In Unity, you can set up multiple light sources to control shadows and lighting, which helps to create realistic depth in the scene. For example, adding a Directional Light
creates the effect of sunlight that illuminates all objects in the scene with the same intensity. In addition, you can apply textures through materials, for example, by applying a wood or stone texture to a cube, which will give the object a realistic appearance. Unity also supports built-in physics, which makes it easy to manage collisions and object interactions. For example, adding a Rigidbody component to an object allows it to respond to gravity and collisions with other objects. The combination of Unity and C# provides powerful capabilities for creating not only games, but also interactive applications and simulations. The flexibility of the C# programming language and the extensive capabilities of Unity allow developers to easily implement complex game mechanics, animations, and user interfaces. Unity supports the use of third-party libraries and tools, such as virtual reality (VR) and augmented reality (AR), which makes the engine in demand for the development of modern applications [2].
Using C# in Unity gives developers the ability to create complex 3D scenes, animations, and physics simulations with high performance. Unity simplifies working with 3D graphics with an intuitive interface and powerful built-in tools, making it an excellent choice for both beginners and experienced developers working with 3D graphics and interactive applications.
Optimizing graphics applications is a key aspect of development, especially when performance is critical. Whether it's games, visual simulations, or complex graphics editors, such applications require high performance to process large amounts of data, provide smooth animation, and provide real-time interactivity. C# applications allow you to use various optimization techniques to improve performance, reduce CPU and GPU load, and minimize rendering delays.
One of the most important tasks when developing graphics applications is to reduce the number of rendering calls. Each call to the graphics API to draw an object can be resource-intensive, especially if there are many such calls. To reduce the load, you can use batching methods to process objects, grouping several objects into one rendering process. This reduces the number of calls and optimizes the rendering of many objects at once. In applications with many similar objects, such as particles or interface elements, it makes sense to combine them into a single data structure and render them as a single unit.
Buffering is another important optimization technique that consists of storing graphic content in memory, which avoids re-rendering unchanged elements. Instead of recalculating and drawing objects each time, an application can store an image in a buffer and display it on the screen without additional calculations. Double buffering prevents visual artifacts such as flickering or tearing by first drawing the image to a hidden buffer and then drawing it to the screen, resulting in smooth and consistent graphics.
Graphics applications can benefit significantly from hardware acceleration, which uses the graphics card (GPU) to process graphics. Rendering operations are offloaded to the graphics card, which can more efficiently handle the parallel calculations required to work with graphics, freeing up the processor (CPU) for other tasks.
In the context of C#, the WPF framework automatically uses hardware acceleration through DirectX for working with graphical elements, including 2D and 3D objects, animations, and textures. This allows applications to run faster and more efficiently on devices that support modern graphics technologies.
Using textures and images in graphics applications requires a significant amount of memory and processor resources. Various methods can be used to optimize working with textures:
Texture compression. Texture compression helps reduce the amount of memory required to store images while maintaining their visual quality. To optimize working with textures, formats such as DXT in DirectX or PVRTC in OpenGL are used, which is especially important for games and applications with a large number of textures.
Lazy loading. Instead of loading all textures at once when the application starts, they can be loaded as needed. This saves memory and speeds up application startup.
Mip mapping. Mip mapping reduces the amount of data required to process textures on distant objects. Mip maps create multiple versions of a single texture with different levels of detail, reducing the load on the GPU when rendering objects located far from the camera.
Memory management is an important part of optimizing graphics applications. In C#, Garbage Collection automatically frees unused objects. However, excessive creation and deletion of objects such as textures or large data structures can cause sudden delays as the garbage collector temporarily pauses program execution to clean up memory. To minimize the impact of garbage collection on performance, you can use the following techniques:
Object reuse. Instead of creating new objects every time you draw, it is recommended to reuse existing objects and data structures, which is especially useful for temporary objects such as textures and geometric primitives.
Manual memory management. In some cases, you can use unsafe code blocks (unsafe in C#) to manage memory more precisely. This increases the risk of memory leaks, but can be useful for critical graphics-related tasks.
Optimization is impossible without a precise understanding of the bottlenecks in the application. To do this, developers need to use profiling tools that allow you to measure the execution time of various operations and identify hot spots in the code. Profiling tools available in C# include Visual Studio Profiler, dotTrace, and others. These tools allow you to analyze the use of resources such as the CPU, GPU, and memory, as well as track the time spent on rendering, event processing, and algorithm execution.
Optimizing graphics applications in C# requires a careful approach to resource management and graphics processing. Key techniques include minimizing rendering calls, using buffering, hardware acceleration, and proper texture management. Performance profiling and analysis help find bottlenecks and improve application efficiency. These techniques allow you to create graphics applications with high performance and smooth rendering, which is especially important in the development of games and interactive applications.
Graphics programming requires high performance, flexibility, and a wide range of tools for working with 2D and 3D graphics. The C# language is widely used in this area due to its tight integration with frameworks such as WPF, GDI+, and the Unity game engine. However, there are other programming languages such as C++, Java, and Python that are also actively used for developing graphics applications. A comparative analysis of C# with these languages allows us to evaluate their advantages and disadvantages in the context of graphical programming [1].
C++ has traditionally been considered one of the most powerful languages for graphics programming, especially in game development and high-performance systems. It is widely used to create graphics engines such as Unreal Engine and CryEngine, as well as libraries such as OpenGL and DirectX. The main advantage of C++ is its low-level control over memory and resources, which makes it ideal for optimizing high-performance graphics applications.
Unlike C++, C# runs in a managed CLR environment, which greatly simplifies memory management and reduces the likelihood of errors related to memory leaks or improper use of resources. This makes C# more convenient for novice developers, as well as for those who prefer to avoid working with low-level aspects of programming. However, this approach can lead to a small performance penalty compared to C++, which can be critical for applications with high performance requirements. C# wins in ease of development and rapid prototyping, while C++ is preferable for creating high-performance graphics engines and applications with increased efficiency requirements.
Java also runs in a managed environment (JVM for Java and CLR for C#), making them similar in terms of memory management and ease of development. Java provides capabilities for creating graphical applications using JavaFX and AWT, but is less used in the field of 3D graphics and games. C# is significantly superior to Java due to its integration with tools such as WPF and Unity, which offer advanced capabilities for creating complex graphical interfaces and high-quality 3D applications. Although Java has advantages in cross-platform and server-side development, its capabilities in the field of high-performance graphics are inferior to C#, which is better suited for creating 3D applications and games [5].
Python is known for its simple syntax and is widely used for rapid prototyping and learning. In graphical programming, Python is applicable in areas such as data visualization and scientific computing, thanks to the Matplotlib, Pygame, and OpenGL libraries. However, Python faces serious limitations when it comes to performance and creating complex graphical applications. One of the main disadvantages of Python is its poor performance compared to C# and C++. Python is interpreted, which makes it slower when handling large amounts of data or rendering complex scenes. Third-party libraries written in C or C++ are often used to improve performance, which can complicate the development process. Thus, C# is significantly superior to Python in developing high-performance graphics applications and games, while Python is preferred for quickly creating simple GUIs and applications that do not require high performance [4].
C# remains a powerful and convenient language for developing graphics applications due to its integration with tools such as Unity, WPF, and GDI+. Compared to C++ and Java, C# offers a simpler development environment while maintaining sufficient performance for most graphics' tasks. Unlike Python, which is popular in data visualization, C# is better suited for creating highperformance games and applications with demanding graphics. Ultimately, the choice of language for graphics programming depends on the specific requirements of the project, such as performance, cross-platform compatibility, or ease of development.
Conclusions. Graphic programming in C# offers developers a wide range of possibilities for creating both simple and complex visual applications. Thanks to integration with tools such as WPF, GDI+ and Unity, C# remains a popular language for developing interactive 2D/3D interfaces and high-performance applications with realistic graphics. These frameworks make C# a versatile tool for creating graphics of varying complexity - from user interfaces to large-scale game projects.
Unity is one of the most popular game engines that uses C# to create interactive 3D applications, games and simulations. Although C# may be inferior to languages such as C++ in terms of maximum performance, its intuitive syntax and convenient development environment make it one of the best options for rapid prototyping and application development. Automatic memory management through the Garbage Collector reduces the likelihood of errors related to
memory leaks and improper use of resources, which is especially important in projects with limited deadlines or when creating prototypes.
Developing high-performance graphics applications in C# requires the use of optimization techniques such as minimizing render calls, buffering, and using hardware acceleration. Comparing C# with other programming languages, it can be noted that C++ remains the preferred choice for developing low-level graphics engines and applications with maximum performance requirements.
Thus, C# has established itself as one of the leading languages for graphics programming, offering a balance between ease of development, powerful tools, and performance. This language remains popular in the field of graphics technologies. In the future, we can expect further development of graphics tools in C#, which will allow developers to create graphics applications even more efficiently and affordably.
REFERENCES
1. Shoyqulov, S. (2024). DATA VISUALIZATION IN PYTHON. Евразийский журнал математической теории и компьютерных наук, 4(10), 15-22. https://in-academy.uz/index.php/EJMTCS/article/view/37502
2. Утегенов Ндадэулет Бауыржанулы. ВИРТУАЛЬНАЯ И ДОПОЛНЕННАЯ РЕАЛЬНОСТИ (VR И AR). https://cyberleninka.ru/article/n/virtualnaya-i-dopolnennaya-realnosti-vr-i-ar/pdf
3. Bozorov, A., Abdulkhayev, N. ., & Shoyqulov, S. . (2022). MODERN TECHNOLOGIES OF VIRTUAL REALITY- A NEW MULTIMEDIA OPPORTUNITIES. Евразийский журнал математической теории и компьютерных наук, 2(11), 85-90. https://in-academy.uz/index.php/EJMTCS/article/view/5376
4. Смирнова М.В. ОСНОВНОЙ ПРИНЦИП ПОСТРОЕНИЯ ГРАФИЧЕСКИХ ОБЪЕКТОВ. https://cyberleninka.ru/article/n/osnovnoy-printsip-postroeniya-graficheskih-obektov
5. Анастасия Юрьевна Чевардина, Владимир Викторович Побединский. ПРИМЕНЕНИЕ API PYTHON В 3D-МОДЕЛИРОВАНИИ BLENDER. Научная статья УДК 004.94. https://elar.usfeu.ru/bitstream/123456789/12849/1/konf 24 091.pdf
6. Шайкулов Б.К., Нуркулов Ф.Н., Джалилов А.Т. /Получение акрил-кротон-уретанового сополимера и анализ его структуры//журнал Universium 9(123), сентября 2024 года, стр. 19-22, DOI-10.32743/UniTech.2024.126.9.18265