{"id":31945,"date":"2024-11-01T09:04:24","date_gmt":"2024-11-01T09:04:24","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=31945"},"modified":"2024-11-01T11:34:03","modified_gmt":"2024-11-01T11:34:03","slug":"basic-unity-course-loops-foreach","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/31945\/","title":{"rendered":"Basic Unity Course: Loops &#8211; foreach"},"content":{"rendered":"<p><body><\/p>\n<p>Hello! In this tutorial, we will take a closer look at one of the very important programming concepts in Unity: loops, particularly the <code>foreach<\/code> statement. Loops provide the ability to process tasks repeatedly, enhancing the utility of the code and allowing us to perform repetitive tasks efficiently. The <code>foreach<\/code> statement is very useful when dealing with iterable data, such as collections (arrays, lists, etc.).<\/p>\n<h2>1. Concept of Loops<\/h2>\n<p>A loop is a structure that repeatedly executes specific code while a specified condition is true. Common loops include <code>for<\/code>, <code>while<\/code>, and <code>foreach<\/code>. Among these, the <code>foreach<\/code> statement allows direct access to each element of a collection, which helps improve code readability and reduce errors.<\/p>\n<h2>2. Basic Structure of the foreach Statement<\/h2>\n<p>The <code>foreach<\/code> statement has the following basic structure.<\/p>\n<pre><code>foreach (dataType variableName in collection) {\n        \/\/ Code to be executed repeatedly\n    }<\/code><\/pre>\n<h3>2.1 Example: Using Arrays<\/h3>\n<p>As a simple example, let\u2019s use the <code>foreach<\/code> statement to output all elements from an array.<\/p>\n<pre><code>using UnityEngine;\n\npublic class ForEachExample : MonoBehaviour\n{\n    void Start()\n    {\n        int[] numbers = { 1, 2, 3, 4, 5 };\n\n        foreach (int number in numbers)\n        {\n            Debug.Log(number);\n        }\n    }\n}<\/code><\/pre>\n<p>In the code above, each element of the <code>numbers<\/code> array is assigned to a variable called <code>number<\/code> one by one, and its value is output to the console.<\/p>\n<h2>3. foreach Statement and Collections<\/h2>\n<p>The <code>foreach<\/code> statement can be used not only with arrays but also with various collections like lists, hash sets, and dictionaries. Let\u2019s look at examples for each type of collection.<\/p>\n<h3>3.1 Using Lists<\/h3>\n<p>A list is a dynamic array structure that allows elements to be added and removed. Here\u2019s an example applying the <code>foreach<\/code> statement using a list.<\/p>\n<pre><code>using System.Collections.Generic;\nusing UnityEngine;\n\npublic class ForEachListExample : MonoBehaviour\n{\n    void Start()\n    {\n        List<string> fruits = new List<string> { \"Apple\", \"Banana\", \"Cherry\", \"Durian\" };\n\n        foreach (string fruit in fruits)\n        {\n            Debug.Log(fruit);\n        }\n    }\n}<\/code><\/pre>\n<p>In this example, each element of the <code>fruits<\/code> list is assigned to the variable <code>fruit<\/code> and then output to the console.<\/p>\n<h3>3.2 Using Hash Sets<\/h3>\n<p>A hash set is a structure that stores unique values and is mainly used to avoid duplicates. Here\u2019s an example using a hash set.<\/p>\n<pre><code>using System.Collections.Generic;\nusing UnityEngine;\n\npublic class ForEachHashSetExample : MonoBehaviour\n{\n    void Start()\n    {\n        HashSet<int> uniqueNumbers = new HashSet<int> { 1, 2, 3, 4, 5, 1, 2 };\n\n        foreach (int number in uniqueNumbers)\n        {\n            Debug.Log(number);\n        }\n    }\n}<\/code><\/pre>\n<p>Here, even though the <code>uniqueNumbers<\/code> hash set contains duplicate numbers, the output values are unique.<\/p>\n<h3>3.3 Using Dictionaries<\/h3>\n<p>A dictionary is a collection of key-value pairs. Here\u2019s an example using a dictionary.<\/p>\n<pre><code>using System.Collections.Generic;\nusing UnityEngine;\n\npublic class ForEachDictionaryExample : MonoBehaviour\n{\n    void Start()\n    {\n        Dictionary<string, int> ageMap = new Dictionary<string, int>\n        {\n            { \"Hong Gil-dong\", 25 },\n            { \"Kim Cheol-su\", 30 },\n            { \"Lee Young-hee\", 28 }\n        };\n\n        foreach (KeyValuePair<string, int> entry in ageMap)\n        {\n            Debug.Log($\"Name: {entry.Key}, Age: {entry.Value}\");\n        }\n    }\n}<\/code><\/pre>\n<p>Using the dictionary&#8217;s <code>KeyValuePair<\/code>, we can output each name and age.<\/p>\n<h2>4. Performance Considerations of the foreach Statement<\/h2>\n<p>The <code>foreach<\/code> statement is very useful, but there are sometimes performance considerations to keep in mind. Particularly when iterating through large collections, performance can become critical. Here are some performance-related considerations when using the <code>foreach<\/code> statement.<\/p>\n<h3>4.1 Memory Allocation<\/h3>\n<p>In some cases, the <code>foreach<\/code> statement may create a copy of the collection and allocate additional memory. This primarily occurs with collections that are not arrays. In performance-critical games, using a <code>for<\/code> statement with direct indexing may be faster.<\/p>\n<h3>4.2 Collection Type<\/h3>\n<p>The memory allocation issue varies depending on the type of collection being used. For example, <code>List<\/code> manages memory efficiently, while <code>LinkedList<\/code> may be relatively slower due to the connections between nodes.<\/p>\n<h2>5. Practical Example Using the foreach Statement<\/h2>\n<p>Now let&#8217;s look at a more practical example using the <code>foreach<\/code> statement.<\/p>\n<h3>5.1 Creating Enemy Characters<\/h3>\n<p>The following example creates enemy characters in an array and uses the <code>foreach<\/code> statement to output the status of each character.<\/p>\n<pre><code>using UnityEngine;\n\npublic class Enemy\n{\n    public string Name;\n    public int Health;\n\n    public Enemy(string name, int health)\n    {\n        Name = name;\n        Health = health;\n    }\n}\n\npublic class EnemyManager : MonoBehaviour\n{\n    void Start()\n    {\n        Enemy[] enemies = {\n            new Enemy(\"Slime\", 100),\n            new Enemy(\"Goblin\", 150),\n            new Enemy(\"Dragon\", 300)\n        };\n\n        foreach (Enemy enemy in enemies)\n        {\n            Debug.Log($\"{enemy.Name}'s Health: {enemy.Health}\");\n        }\n    }\n}<\/code><\/pre>\n<h3>5.2 My Own Object Pooling Example<\/h3>\n<p>Object Pooling is a pattern used to efficiently manage game objects that are frequently created and destroyed. Here\u2019s a simple class example for object pooling.<\/p>\n<pre><code>using System.Collections.Generic;\nusing UnityEngine;\n\npublic class Bullet\n{\n    public GameObject bulletObject;\n}\n\npublic class ObjectPool : MonoBehaviour\n{\n    private List<Bullet> bulletPool;\n\n    void Start()\n    {\n        bulletPool = new List<Bullet>();\n        for (int i = 0; i < 10; i++)\n        {\n            Bullet bullet = new Bullet();\n            bullet.bulletObject = CreateBullet();\n            bulletPool.Add(bullet);\n        }\n\n        foreach (Bullet bullet in bulletPool)\n        {\n            Debug.Log(\"Bullet created: \" + bullet.bulletObject.name);\n        }\n    }\n\n    GameObject CreateBullet()\n    {\n        GameObject bullet = new GameObject(\"Bullet\");\n        \/\/ Bullet initialization code\n        return bullet;\n    }\n}<\/code><\/pre>\n<h2>6. Conclusion<\/h2>\n<p>In this tutorial, we explored loops in Unity, particularly the <code>foreach<\/code> statement. The <code>foreach<\/code> statement allows us to traverse various collection types, making the code more concise and readable. However, we should not forget about performance considerations and it\u2019s important to use it appropriately alongside other loops. This will enable us to handle repetitive tasks efficiently during game development.<\/p>\n<p>Use the various elements of Unity to create an amazing game! Thank you.<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello! In this tutorial, we will take a closer look at one of the very important programming concepts in Unity: loops, particularly the foreach statement. Loops provide the ability to process tasks repeatedly, enhancing the utility of the code and allowing us to perform repetitive tasks efficiently. The foreach statement is very useful when dealing &hellip; <a href=\"https:\/\/atmokpo.com\/w\/31945\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Basic Unity Course: Loops &#8211; foreach&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[135],"tags":[],"class_list":["post-31945","post","type-post","status-publish","format-standard","hentry","category-unity-basic"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Basic Unity Course: Loops - foreach - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/31945\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Basic Unity Course: Loops - foreach - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"Hello! In this tutorial, we will take a closer look at one of the very important programming concepts in Unity: loops, particularly the foreach statement. Loops provide the ability to process tasks repeatedly, enhancing the utility of the code and allowing us to perform repetitive tasks efficiently. The foreach statement is very useful when dealing &hellip; \ub354 \ubcf4\uae30 &quot;Basic Unity Course: Loops &#8211; foreach&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/31945\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:04:24+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:34:03+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"4\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/31945\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/31945\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Basic Unity Course: Loops &#8211; foreach\",\"datePublished\":\"2024-11-01T09:04:24+00:00\",\"dateModified\":\"2024-11-01T11:34:03+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/31945\/\"},\"wordCount\":574,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Unity Basic\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/31945\/\",\"url\":\"https:\/\/atmokpo.com\/w\/31945\/\",\"name\":\"Basic Unity Course: Loops - foreach - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:04:24+00:00\",\"dateModified\":\"2024-11-01T11:34:03+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/31945\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/31945\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/31945\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Basic Unity Course: Loops &#8211; foreach\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Basic Unity Course: Loops - foreach - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/31945\/","og_locale":"ko_KR","og_type":"article","og_title":"Basic Unity Course: Loops - foreach - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"Hello! In this tutorial, we will take a closer look at one of the very important programming concepts in Unity: loops, particularly the foreach statement. Loops provide the ability to process tasks repeatedly, enhancing the utility of the code and allowing us to perform repetitive tasks efficiently. The foreach statement is very useful when dealing &hellip; \ub354 \ubcf4\uae30 \"Basic Unity Course: Loops &#8211; foreach\"","og_url":"https:\/\/atmokpo.com\/w\/31945\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:04:24+00:00","article_modified_time":"2024-11-01T11:34:03+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"4\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/31945\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/31945\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Basic Unity Course: Loops &#8211; foreach","datePublished":"2024-11-01T09:04:24+00:00","dateModified":"2024-11-01T11:34:03+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/31945\/"},"wordCount":574,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Unity Basic"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/31945\/","url":"https:\/\/atmokpo.com\/w\/31945\/","name":"Basic Unity Course: Loops - foreach - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:04:24+00:00","dateModified":"2024-11-01T11:34:03+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/31945\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/31945\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/31945\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Basic Unity Course: Loops &#8211; foreach"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/31945","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=31945"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/31945\/revisions"}],"predecessor-version":[{"id":31946,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/31945\/revisions\/31946"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=31945"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=31945"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=31945"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}