0
votes

I am designing a game and one of the fundamentals is to load a text file formatted like:

11111111111-
00200000001-
10202220101-
10001010101-
11101010101-
10001010101-
11111011101-
10001000101-
10111110101-
10000000000-
11111111111

Each integer within the file will relate to a specific prefab within the game. Therefore, if the integer is 1 then the program will instantiate a "brick" prefab, if the integer is 2 then the program will instantiate a "brokenBrick" prefab and if the integer is 0 then nothing is spawned.

So far I have:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


class Instantiate : MonoBehaviour
{
    public GameObject Brick = null;
    public GameObject brokenBrick = null;
    private string TempLoad;
    private string IDChar;

    void Start()
    {
        int x = 0;
        int y = 0;
        TempLoad = System.IO.File.ReadAllText(@"\Assets\Resources\Worlds\lvl1.txt");
        foreach (char c in TempLoad)
        {
            IDChar = TempLoad[c].ToString();
            if (IDChar == "1")
            {
                Instantiate(Brick, new Vector2(x, y), Quaternion.identity);
                x += 1;
            }
            else if (IDChar == "2")
            {
                Instantiate(brokenBrick, new Vector2(x, y), Quaternion.identity);
                x += 1;

            }
            else if (IDChar == "0")
            {
                x += 1;
            }
            else if(IDChar == "-")
            {
                y += 1;
            }

        }

    }
}

I have this attached to my game objects and my prefabs dragged into the sections within the instantiate script in my game object. However nothing spawns. I am unsure why nothing is spawning even though the program should be instantiating the prefabs?

1
Don't compare strings using == - Draco18s no longer trusts SE
@Draco18s I tried changing it down to just a singular = but visual studio says I am trying to compare a string to a boolean - Roodolpha
@Roodolpha A single '=` is for assigning value, not comparing - Eliasar
Oh, thankyou for clarifying, I am fairly new to c# to still learning :) - Roodolpha

1 Answers

0
votes

Make sure that your code is entering the condition blocks.

 if (IDChar == "1")
 {
     Debug.Log("1 detected");
     Instantiate(Brick, new Vector2(x, y), Quaternion.identity);
     x += 1;
 }

Also, use string.Equals(string) for value comparisons versus == operator, which is a reference comparison.

 if (IDChar.Equals("1"))
 {
     Instantiate(Brick, new Vector2(x, y), Quaternion.identity);
     x += 1;
 }