Unity hatalı kod örneği verir misiniz?

721893

Centipat
Katılım
12 Ekim 2023
Mesajlar
52
Ben Unity ile programlama öğrenmeye çalışıyorum o yüzden düzeltmek için hatalı olarak yazılmış kodlar arıyorum bir projede biçiminde
 
Son düzenleme:
Kolay
Kod:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using TMPro;

using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
using UnityEditor;

public class MainUIManager : MonoBehaviour
{
    public GameObject sentenceMenuPanel;
    public TextMeshProUGUI sentenceMenuPanelText;
    public GameObject achievementsButton;

    public GameObject iapPanel;

    public Locale[] locales;

    void Start()
    {
        LocalizationSettings.SelectedLocale = locales[(int)PlayerPrefs.GetFloat("Language")];

        UpdateLanguageButton();
    }
    public void OpenIAPPanel()
    {
        iapPanel.SetActive(true);
    }
    public void SentenceMenuCloseButton()
    {
        sentenceMenuPanel.SetActive(false);
    }

    public void AchievementsOpenButton(bool value)
    {
        achievementsButton.SetActive(value);
    }


    [Header("Settings")]
    public GameObject settingsPanel;
    public GameObject languagePanel;
    public void SettingsButtons(string i)
    {
        if (i == "Open")
        {
            settingsPanel.SetActive(true);
        }
        if (i == "Close")
        {
            settingsPanel.SetActive(false);
        }
        if (i == "Open Language")
        {
            languagePanel.SetActive(true);
        }
        if (i == "Close Language")
        {
            languagePanel.SetActive(false);
        }
    }
    public void LanguageButtons(Locale code)
    {
        for (int i = 0; i != locales.Length; i++)
        {
            if(locales[i] == code)
            {
                PlayerPrefs.SetFloat("Language", i);
            }
        }

        LocalizationSettings.SelectedLocale = code;

        languagePanel.SetActive(false);

        UpdateLanguageButton();
    }
    public TextMeshProUGUI activeLanguageButton;
    public void UpdateLanguageButton()
    {
        activeLanguageButton.text = LocalizationSettings.SelectedLocale.ToString();
    }

    public GameObject pausePanel;
    public void PasuePanelButtons(string i)
    {
        if(i == "Pause")
        {
            Time.timeScale = 0
            pausePanel.SetActive(true);
        }
        if(i == "Continue")
        {
            Time.timeScale = 1;
            pausePanel.SetActive(false);
        }
        if(i == "MainMenu")
        {
            Time.timeScale = 1;
            Application.LoadLevel(Application.loadedLevel);
        }
    }
}

Orta
Kod:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.tag == "WallChild")
        {
            other.transform.parent.GetComponentInParent<SmashObjects>().Explode(transform);

            Destroy(GetComponent<Ball>()));
        }
    }
}

Zor
Kod:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using TMPro;
using Unity.VisualScripting;

using Firebase.Database;
using static Firebase.Extensions.TaskExtension;

using PlayFab;
using PlayFab.ClientModels;
public class PlayerController : MonoBehaviour
{
    public bool roomGame;
    public float roomQueue;
    public GameObject ballPrefab;
    public float ballThrowSpeed;

    public bool canMove;

    public Transform lookObject;
    public float lookObjectAxisZ;

    public float ballAmount = 15;
    public TextMeshProUGUI ballText;
    public TextMeshProUGUI distanceText;

    public GameObject menuPanel;
    public GameObject gamePanel;
    public GameObject hearthBuyPanel;

    public Transform startPos;
    public GameObject damageGet;

    public TextMeshProUGUI bestDistanceText;

    public GameObject map1, map2;

    [Header("Start Positions")]
    Vector3 map1Pos;
    Vector3 map2Pos;
    Vector3 playerStartPos;

    void Start()
    {
        map1Pos = map1.transform.localPosition;
        map2Pos = map2.transform.localPosition;
        playerStartPos = transform.localPosition;

        UpdateBestScoreText();
        UpdateCoinPanels();

        ballText.text = ballAmount.ToString();
    }
    public void UpdateBallText()
    {
        ballText.text = ballAmount.ToString();
    }

    bool gameEnded;
    public GameObject gameOverPanel;
    int gameTime;
    Coroutine timerCoroutine;
    private void FixedUpdate()
    {
        if (ballAmount == 0 && !gameEnded && !roomGame)
        {
            StartCoroutine(GameOver());

            gameEnded = true;
        }

        if (ballAmount == 0 && !gameEnded && roomGame)
        {
            StartCoroutine((GameOverRoomMode()));

            gameEnded = true;
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("Space Pressed");
        }

        if (Input.GetMouseButtonDown(0) && !canShoot && canMove)
        {
            if (ballAmount > 0)
            {
                Vector3 finger2Pos = Input.mousePosition;

                Vector3 posit2 = finger2Pos;
                posit2.z = lookObjectAxisZ;
                Vector3 realWorldPos2 = Camera.main.ScreenToWorldPoint(posit2);

                ThrowBall(realWorldPos2);

                ballAmount -= 1;
                ballText.text = ballAmount.ToString();

                canShoot = true;
                StartCoroutine(Shooted());
            }
        }
        if (Input.touchCount > 1 && !canShoot && canMove)
        {
            if (ballAmount > 0)
            {
                Vector3 fingerPos = Input.GetTouch(0).position;

                Vector3 posit = fingerPos;
                posit.z = lookObjectAxisZ;
                Vector3 realWorldPos = Camera.main.ScreenToWorldPoint(posit);

                ThrowBall(realWorldPos);

                ballAmount -= 1;
                ballText.text = ballAmount.ToString();

                canShoot = true;
                StartCoroutine(Shooted());
            }
        }
        if (canMove)
        {
            transform.position += transform.TransformDirection(Vector3.forward * speed);
        }
    }
    public void UpdateBestScoreText()
    {
        bestDistanceText.text = PlayerPrefs.GetFloat("Best Score").ToString();
    }
    bool canShoot;
    IEnumerator Shooted()
    {
        yield return new WaitForSeconds(0.3f);

        canShoot = false;
    }
    public void ContinueGame()
    {
        canMove = true;

        gameOverPanel.SetActive(false);

        gameEnded = false;

        ballAmount = 15;
        ballText.text = ballAmount.ToString();
    }

    public IEnumerator GameOver()
    {
        StopCoroutine(timerCoroutine);

        if (PlayerPrefs.GetFloat("Best Score") > float.Parse(distanceText.text))
        {
            PlayerPrefs.SetFloat("Best Score", float.Parse(distanceText.text));
        }

        canMove = false;
        yield return new WaitForSeconds(3f);

        gameOverPanel.SetActive(true);

        if (PlayerPrefs.GetString("username") != string.Empty)
        {
            SendScore();
        }
    }
    void SendScore()
    {
        var request = new LoginWithCustomIDRequest
        {
            CreateAccount = true,
            CustomId = PlayerPrefs.GetString("username")
        };

        PlayFabClientAPI.LoginWithCustomID(request, SendLeaderboard, Failed);
    }
    void SendLeaderboard(LoginResult result)
    {
        PlayFabClientAPI.UpdatePlayerStatistics(new UpdatePlayerStatisticsRequest
        {
            Statistics = new List<StatisticUpdate> {
            new StatisticUpdate {
                StatisticName = "Wekkly",
                Value = int.Parse(distanceText.text)
            }
        }

        }, result => Debug.Log(result), Failed);

        PlayFabClientAPI.UpdatePlayerStatistics(new UpdatePlayerStatisticsRequest
        {
            Statistics = new List<StatisticUpdate> {
            new StatisticUpdate {
                StatisticName = "AllTime",
                Value = int.Parse(distanceText.text)
            }
        }

        }, result => Debug.Log(result), Failed);

        PlayFabClientAPI.UpdateUserTitleDisplayName(new UpdateUserTitleDisplayNameRequest
        {
            DisplayName = PlayerPrefs.GetString("username"),

        }, result => Debug.Log(result), Failed, null, null);
    }
    void Failed(PlayFabError error)
    {
        Debug.Log(error);
    }

    public GameObject roomGameOverPanel;
    public IEnumerator GameOverRoomMode()
    {
        canMove = false;
        yield return new WaitForSeconds(3f);

        roomGameOverPanel.SetActive(true);
    }

    public void EarnModeGameOverButtons()
    {
        StartCoroutine(EarnModeGameOverTransaction());
    }

    IEnumerator EarnModeGameOverTransaction()
    {
        StopCoroutine(timerCoroutine);

        roomGameOverPanel.SetActive(false);

        FindObjectOfType<AccountSystem>().loadingPanel.SetActive(true);

        float roomCoin = 0;
        FirebaseDatabase.DefaultInstance.GetReference("Rooms").Child("Room" + roomQueue).Child("collectedCoins").GetValueAsync()
        .ContinueWithOnMainThread(task =>
        {
            roomCoin = float.Parse(task.Result.Value.ToString());
        });

        float users = 0;
        FirebaseDatabase.DefaultInstance.GetReference("Rooms").Child("Room" + roomQueue).Child("Users").Child("playedUsers").GetValueAsync()
        .ContinueWithOnMainThread(task =>
        {
            users = float.Parse(task.Result.Value.ToString());
        });

        yield return new WaitForSeconds(2);

        float newCoin = roomCoin + float.Parse(distanceText.text);
        FirebaseDatabase.DefaultInstance.GetReference("Rooms").Child("Room" + roomQueue).Child("collectedCoins").SetValueAsync(newCoin);

        yield return new WaitForSeconds(2);

        float thisUser = users + 1;
        FirebaseDatabase.DefaultInstance.GetReference("Rooms").Child("Room" + roomQueue).Child("Users").Child("Player" + thisUser).Child("username").SetValueAsync(PlayerPrefs.GetString("username"));
        FirebaseDatabase.DefaultInstance.GetReference("Rooms").Child("Room" + roomQueue).Child("Users").Child("Player" + thisUser).Child("score").SetValueAsync(distanceText.text);
        FirebaseDatabase.DefaultInstance.GetReference("Rooms").Child("Room" + roomQueue).Child("Users").Child("playedUsers").SetValueAsync(thisUser);

        gamePanel.SetActive(false);
        menuPanel.SetActive(true);

        FindObjectOfType<AccountSystem>().roomPanel.SetActive(false);

        UpdateBestScoreText();

        FindObjectOfType<AccountSystem>().loadingPanel.SetActive(false);

        map1.transform.localPosition = map1Pos;
        map2.transform.localPosition = map2Pos;
        transform.localPosition = playerStartPos;

        foreach (var item in map1.GetComponentsInChildren<SmashObjects>())
        {
            item.Restart();
        }

        foreach (var item in map1.GetComponentsInChildren<RestartTargets>())
        {
            foreach (var t in item.GetComponentsInChildren<SmashObjects>())
            {
                t.Restart();
            }
        }

        foreach (var item in map2.GetComponentsInChildren<SmashObjects>())
        {
            item.Restart();
        }

        foreach (var item in map2.GetComponentsInChildren<RestartTargets>())
        {
            foreach (var t in item.GetComponentsInChildren<SmashObjects>())
            {
                t.Restart();
            }
        }
    }

    public void GameOverMainMenuButton()
    {
        StartCoroutine(EndGameTransactions());
    }
    IEnumerator EndGameTransactions()
    {
        FindObjectOfType<AccountSystem>().loadingPanel.SetActive(true);
        gameOverPanel.SetActive(false);
        

        if (PlayerPrefs.GetString("username") != string.Empty)
        {
            menuPanel.SetActive(true);
            gamePanel.SetActive(false);

            float coin = 0;
            FirebaseDatabase.DefaultInstance.GetReference("Users").Child(PlayerPrefs.GetString("username")).Child("coin").GetValueAsync()
            .ContinueWithOnMainThread(task => { coin = float.Parse(task.Result.Value.ToString()); });

            yield return new WaitForSeconds(3);

            float newCoin = float.Parse(distanceText.text) + coin;
            FirebaseDatabase.DefaultInstance.GetReference("Users").Child(PlayerPrefs.GetString("username")).Child("coin").SetValueAsync(newCoin);

            PlayerPrefs.SetFloat("Coin", newCoin);

            UpdateCoinPanels();
        }
        else
        {
            menuPanel.SetActive(true);
            gamePanel.SetActive(false);

            float coin = PlayerPrefs.GetFloat("Coin");

            float newCoin = float.Parse(distanceText.text) + coin;

            PlayerPrefs.SetFloat("Coin", newCoin);

            UpdateCoinPanels();
        }

        map1.transform.localPosition = map1Pos;
        map2.transform.localPosition = map2Pos;
        transform.localPosition = playerStartPos;

        foreach (var item in map1.GetComponentsInChildren<SmashObjects>())
        {
            item.Restart();
        }

        foreach (var item in map1.GetComponentsInChildren<RestartTargets>())
        {
            foreach (var t in item.GetComponentsInChildren<SmashObjects>())
            {
                t.Restart();
            }
        }

        foreach (var item in map2.GetComponentsInChildren<SmashObjects>())
        {
            item.Restart();
        }

        foreach (var item in map2.GetComponentsInChildren<RestartTargets>())
        {
            foreach (var t in item.GetComponentsInChildren<SmashObjects>())
            {
                t.Restart();
            }
        }

        FindObjectOfType<AccountSystem>().loadingPanel.SetActive(false);
    }
    public void PausePanelMainMenuButton()
    {
        FindObjectOfType<MainUIManager>().pausePanel.SetActive(false);

        gameOverPanel.SetActive(false);

        menuPanel.SetActive(true);
        gamePanel.SetActive(false);

        map1.transform.localPosition = map1Pos;
        map2.transform.localPosition = map2Pos;
        transform.localPosition = playerStartPos;

        foreach (var item in map1.GetComponentsInChildren<SmashObjects>())
        {
            item.Restart();
        }

        foreach (var item in map1.GetComponentsInChildren<RestartTargets>())
        {
            foreach (var t in item.GetComponentsInChildren<SmashObjects>())
            {
                t.Restart();
            }
        }

        foreach (var item in map2.GetComponentsInChildren<SmashObjects>())
        {
            item.Restart();
        }

        foreach (var item in map2.GetComponentsInChildren<RestartTargets>())
        {
            foreach (var t in item.GetComponentsInChildren<SmashObjects>())
            {
                t.Restart();
            }
        }

        FindObjectOfType<HearthSystem>().CheckHearths();
    }
    IEnumerator DamagePanel()
    {
        damaged = true;
        damageGet.SetActive(true);

        yield return new WaitForSeconds(1);

        damageGet.SetActive(false);
        damaged = false;
    }
    bool damaged;

    public GameObject sentencesPanel;
    public TextMeshProUGUI sentencesText;
    public string[] sentences;
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "WallChild" && !damaged)
        {
            if (ballAmount - 5 < 0)
            {
                ballAmount = 0;
            }
            else
            {
                ballAmount -= 5;
            }
            ballText.text = ballAmount.ToString();

            StartCoroutine(DamagePanel());
        }
        if (other.gameObject.tag == "Map")
        {
            other.transform.position += new Vector3(0, 0, 272);

            var child = other.gameObject.transform.GetChild(0);

            int random = Random.Range(0, 4); //0 1 2 4
            child.transform.localRotation = Quaternion.Euler(child.transform.localEulerAngles.x, random * 90, child.transform.localEulerAngles.z);

            foreach (var item in child.GetComponentsInChildren<SmashObjects>())
            {
                item.Restart();
            }

            foreach (var item in child.GetComponentsInChildren<RestartTargets>())
            {
                foreach (var t in item.GetComponentsInChildren<SmashObjects>())
                {
                    t.Restart();
                }
            }
        }
        if (other.gameObject.tag == "MapTargetCollider")
        {
            sentencesPanel.SetActive(true);

            int i = Random.Range(0, 100);

            sentencesText.text = sentences[i];
            PlayerPrefs.SetFloat(sentences[i], 1);

            Time.timeScale = 0;

            speed += 0.045f;
        }
    }
    public void SentencesContinueButton()
    {
        Time.timeScale = 1;

        sentencesPanel.SetActive(false);
    }

    [Header("Hearth Panel")]
    public TextMeshProUGUI[] hearthsText;
    public void UpdateHearths()
    {
        foreach (var item in hearthsText)
        {
            item.text = PlayerPrefs.GetFloat("Hearth Amount").ToString();
        }
    }
    public void CloseHearthsPanel()
    {
        hearthBuyPanel.SetActive(false);
    }

    public void PlayGameButton()
    {
        if (PlayerPrefs.GetFloat("Hearth Amount") != 0)
        {
            ballAmount = 15;
            ballText.text = ballAmount.ToString();

            menuPanel.SetActive(false);
            gamePanel.SetActive(true);

            FindObjectOfType<AccountSystem>().loadingPanel.SetActive(false);
            FindObjectOfType<AccountSystem>().roomPanel.SetActive(false);

            canMove = true;

            PlayerPrefs.SetFloat("Hearth Amount", PlayerPrefs.GetFloat("Hearth Amount") - 1);

            UpdateHearths();

            gameTime = 0;

            timerCoroutine = StartCoroutine(TimerLoop());
        }
        else
        {
            hearthBuyPanel.SetActive(true);
        }
    }

    public IEnumerator TimerLoop()
    {
        if (!gameEnded)
        {
            gameTime += 1;
            distanceText.text = gameTime.ToString();

            yield return new WaitForSeconds(1);

            StartCoroutine(TimerLoop());
        }
        else
        {
            yield break;
        }
    }
    void ThrowBall(Vector3 throwPos)
    {
        lookObject.transform.position = throwPos;

        var ball = Instantiate(ballPrefab, transform.position, Quaternion.identity);
        ball.transform.LookAt(lookObject);

        var ballRgb = ball.GetComponent<Rigidbody>();
        ballRgb.AddForce(ballRgb.transform.TransformDirection(Vector3.forward * ballThrowSpeed));

        BallDestroyTime(ball);
    }
    IEnumerator BallDestroyTime(GameObject ball)
    {
        yield return new WaitForSeconds(10f);

        Destroy(ball.gameObject);

        yield break;
    }

    public TextMeshProUGUI[] coinPanelTexts;
    public void UpdateCoinPanels()
    {
        float coin = PlayerPrefs.GetFloat("Coin");
        foreach (var item in coinPanelTexts)
        {
            item.text = coin.ToString();
        }
    }
}

Çok Zor
Kod:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Localization;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public Color[] targetLightColors;
    public Light cameraPointLight;
    public float changeCameraColorSpeed;
    public Material mapMaterial;

    bool changeCameraLight;
    int activeColorValue;
    Color lightColor;

    public GameObject needInternetPanel;

    private void Start()
    {
        if(Application.internetReachability == NetworkReachability.NotReachable)
        {
            needInternetPanel.SetActive(true);
        }
        CameraLightLoop();
    }
    private void Update()
    {
        if (cameraPointLight.color == lightColor)
        {
            CameraColorChange(activeColorValue + 1);
        }
        if (changeCameraLight)
        {
            cameraPointLight.color = Color.Lerp(cameraPointLight.color, lightColor, changeCameraColorSpeed * Time.deltaTime);

            RenderSettings.fogColor = Color.Lerp(cameraPointLight.color, lightColor, changeCameraColorSpeed * Time.deltaTime);

            mapMaterial = Color.Lerp(cameraPointLight.color, lightColor, changeCameraColorSpeed * Time.deltaTime);
        }
    }
    public void NeedInternetConnectionPanelOkButton()
    {
        Application.LoadLevel(Application.loadedLevel);
    }
    void CameraLightLoop()
    {
        CameraColorChange(0);
    }
    void CameraColorChange(int i)
    {
        if(i != 8 || i < 8)
        {
            lightColor = targetLightColors[i];

            activeColorValue = i;
        }
        else
        {
            lightColor = targetLightColors[0];

            activeColorValue = 0;
        }
        
        if (!changeCameraLight)
        {
            changeCameraLight = true;
        }
    }
}
 
Bu siteyi kullanmak için çerezler gereklidir. Siteyi kullanmaya devam etmek için çerezleri kabul etmelisiniz. Daha Fazlasını Öğren.…