Forum begins after the advertisement:

 


[Part 14] MissingReferenceException with RectTransform

Home Forums Video Game Tutorial Series Creating a Rogue-like Shoot-em Up in Unity [Part 14] MissingReferenceException with RectTransform

Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #18341
    Kim Il Woo (FGW HCM)
    Level 5
    Participant
    Helpful?
    Up
    0
    ::
    MissingReferenceException: The object of type 'UnityEngine.RectTransform' has been destroyed but you are still trying to access it.
    Your script should either check if it is null or you should not destroy the object.
    UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <c01a2e87500f4b88b40eba7308bfcbe6>:0)
    UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <c01a2e87500f4b88b40eba7308bfcbe6>:0)
    UnityEngine.Transform.set_position (UnityEngine.Vector3 value) (at <c01a2e87500f4b88b40eba7308bfcbe6>:0)
    GameManager+<GenerateFloatingTextCoroutine>d__31.MoveNext () (at Assets/Scripts/GameManager.cs:153)
    UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <c01a2e87500f4b88b40eba7308bfcbe6>:0)
    UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
    MissingReferenceException: The object of type 'UnityEngine.Transform' has been destroyed but you are still trying to access it.
    Your script should either check if it is null or you should not destroy the object.
    UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <c01a2e87500f4b88b40eba7308bfcbe6>:0)
    UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <c01a2e87500f4b88b40eba7308bfcbe6>:0)
    UnityEngine.Transform.get_position () (at <c01a2e87500f4b88b40eba7308bfcbe6>:0)
    GameManager+<GenerateFloatingTextCoroutine>d__31.MoveNext () (at Assets/Scripts/GameManager.cs:153)
    UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <c01a2e87500f4b88b40eba7308bfcbe6>:0)
    UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

    How can I fix this error it say something about the line 153 which is this line rect.position = referenceCamera.WorldToScreenPoint(target.position + new Vector3(0, yOffset));

    #18342
    Terence
    Level 31
    Keymaster
    Helpful?
    Up
    0
    ::

    It is saying that your target variable is null, so target.position fails because it becomes null.position.

    Can you share your entire script here?

    #18343
    Alp Apustaja
    Level 9
    AI Assistant
    (BETA)
    Helpful?
    Up
    1
    ::

    Add null checks before accessing target and rect:

    if (target != null && rect != null) {
        rect.position = referenceCamera.WorldToScreenPoint(target.position + new Vector3(0, yOffset));
    }

    This will prevent accessing destroyed objects and stop the MissingReferenceException.

    has upvoted this post.
    #18347
    Kim Il Woo (FGW HCM)
    Level 5
    Participant
    Helpful?
    Up
    0
    ::

    Thanks for answering this error of mine but now im currently having error at part 15 which i have already posted in the forum

    #18348
    Alp Apustaja
    Level 9
    AI Assistant
    (BETA)
    Helpful?
    Up
    0
    ::

    I can help you with that! Please provide the details of the error you’re encountering at part 15, along with any relevant code snippets. This way, I can better assist you in resolving the issue.

    #18408
    Kim Il Woo (FGW HCM)
    Level 5
    Participant
    Helpful?
    Up
    0
    ::
    using UnityEngine;
    using UnityEngine.UI;
    using TMPro;
    using System;
    using System.Collections.Generic;
    using System.Collections;
    
    public class GameManager : MonoBehaviour
    {
        public static GameManager instance;
        //define different state of the game
        public enum GameState
        {
            Gameplay,
            Paused,
            GameOver,
            LeveUp
        }
    
        //store the current state of the game
        public GameState currentState;
    
        //store previous game state
        public GameState previouseState;
    
        [Header("Damage Text Setting")]
        public Canvas damageTextCanvas;
        public float textFontSize = 50;
        public TMP_FontAsset textFont;
        public Camera referenceCamera;
    
        [Header("Screens")]
        public GameObject pauseScreen;
        public GameObject resultsScreen;
        public GameObject levelUpScreen;
        int stackedLevelUps = 0;
    
        [Header("Current State Display")]
        public TMP_Text currentHealthDisplay;
        public TMP_Text currentRecoveryDisplay;
        public TMP_Text currentMoveSpeedDisplay;
        public TMP_Text currentMightDisplay;
        public TMP_Text currentProjectileSpeedDisplay;
        public TMP_Text currentMagnetDisplay;
    
        [Header("Results Screen Displays")]
        public Image chosenCharacterImage;
        public TMP_Text chosenCharacterName;
        public TMP_Text levelReachedDisplay;
        public TMP_Text timeSurviveDisplay;
        public List<Image> chosenWeaponsUI = new List<Image>(6);
        public List<Image> chosenPassiveItemsUI = new List<Image>(6);
    
        [Header("Stopwatch")]
        public float timeLimit;
        float stopwatchTime;
        public TMP_Text stopwatchDisplay;
    
        //refernce to the player object
        public GameObject playerObject;
    
        public bool isGameOver { get { return currentState == GameState.GameOver; } }
        public bool choosingUpgrade{get { return currentState == GameState.LeveUp; }}
    
        public float GetElapsedTime() { return stopwatchTime; }
    
        void Awake()
        {
            //warning to check if there is also a singleton of this kind in the game
            if (instance == null)
            {
                instance = this;
            }
            else
            {
                Debug.LogWarning("extra" + this + "deleted");
                Destroy(gameObject);
            }
    
            DisableScreen();
        }
    
        void Update()
        {
    
            switch (currentState)
            {
                case GameState.Gameplay:
                    //code for gameplay state
                    CheckForPauseAndResume();
                    UpdateStopWatch();
                    break;
    
                case GameState.Paused:
                    //code for pause state
                    CheckForPauseAndResume();
                    break;
    
                case GameState.GameOver:
                    //code for gameover state
                    break;
                case GameState.LeveUp:
                    break;
    
                default:
                    Debug.LogWarning("State dont exist");
                    break;
            }
        }
    
        IEnumerator GenerateFloatingTextCoroutine(string text, Transform target, float duration = 1f, float speed = 50f)
        {
            GameObject textObj = new GameObject("Damage Floating Text");
            RectTransform rect = textObj.AddComponent<RectTransform>();
            TextMeshProUGUI tmPro = textObj.AddComponent<TextMeshProUGUI>();
            tmPro.text = text;
            tmPro.horizontalAlignment = HorizontalAlignmentOptions.Center;
            tmPro.verticalAlignment = VerticalAlignmentOptions.Middle;
            tmPro.fontSize = textFontSize;
            if (textFont) tmPro.font = textFont;
            rect.position = referenceCamera.WorldToScreenPoint(target.position);
    
            Destroy(textObj, duration);
    
            textObj.transform.SetParent(instance.damageTextCanvas.transform);
            textObj.transform.SetSiblingIndex(0);
    
    
            WaitForEndOfFrame w = new WaitForEndOfFrame();
            float t = 0;
            float yOffset = 0;
            while (t < duration)
            {
                tmPro.color = new Color(tmPro.color.r, tmPro.color.g, tmPro.color.b, 1 - t / duration);
    
                if(target)
                {
                    yOffset += speed * Time.deltaTime;
                    rect.position = referenceCamera.WorldToScreenPoint(target.position + new Vector3(0,yOffset));
                } else
                {
                    // If target is dead, just pan up where the text is at.
                    rect.position += new Vector3(0, speed * Time.deltaTime, 0);
                }
                yield return w;
                t += Time.deltaTime;
            }
    
        }
    
        public static void GenerateFloatingText(string text, Transform target, float duration = 1f, float speed = 1f)
        {
            if (!instance.damageTextCanvas) return;
    
            if (!instance.referenceCamera) instance.referenceCamera = Camera.main;
    
            instance.StartCoroutine(instance.GenerateFloatingTextCoroutine(text, target, duration, speed));
        }
    
        //define the method to change game state
        public void ChangeState(GameState newState)
        {
            previouseState = currentState;
            currentState = newState;
        }
    
        public void PauseGame()
        {
            if (currentState != GameState.Paused)
            {
                ChangeState(GameState.Paused);
                Time.timeScale = 0f; //stop the game
                pauseScreen.SetActive(true);
            }
        }
    
        public void ResumeGame()
        {
            if (currentState == GameState.Paused)
            {
                ChangeState(previouseState);
                Time.timeScale = 1f; //resume game
                pauseScreen.SetActive(false);
            }
        }
    
        void CheckForPauseAndResume()
        {
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                if (currentState == GameState.Paused)
                {
                    ResumeGame();
                }
                else
                {
                    PauseGame();
                }
            }
        }
    
        void DisableScreen()
        {
            pauseScreen.SetActive(false);
            resultsScreen.SetActive(false);
            levelUpScreen.SetActive(false);
        }
    
        public void GameOver()
        {
            timeSurviveDisplay.text = stopwatchDisplay.text;
    
            ChangeState(GameState.GameOver);
            Time.timeScale = 0f;
            DisplayResults();
        }
    
        void DisplayResults()
        {
            resultsScreen.SetActive(true);
        }
    
        public void AssignChosenCharacterUI(CharacterData chosenCharacterData)
        {
            chosenCharacterImage.sprite = chosenCharacterData.Icon;
            chosenCharacterName.text = chosenCharacterData.name;
        }
    
        public void AssignLevelReachedUI(int levelReachedData)
        {
            levelReachedDisplay.text = levelReachedData.ToString();
        }
    
        public void AssignChosenWeaponsAndPassiveItemsUI(List<PlayerInventory.Slot> chosenWeaponsData, List<PlayerInventory.Slot> chosenPassiveItemsData)
        {
            if (chosenWeaponsData.Count != chosenWeaponsUI.Count || chosenPassiveItemsData.Count != chosenPassiveItemsUI.Count)
            {
                Debug.Log("chosen weapon and passive list have different length");
                return;
            }
    
            //assign chosen weapon data to chosenweaponUI
            for (int i = 0; i < chosenWeaponsUI.Count; i++)
            {
                //check the sprite of the correspoding element in chosenWeaponData is not null
                if (chosenWeaponsData[i].image.sprite)
                {
                    //enable the corresponding in chosenWeaponUI and set it sprite to the corresponding sprite in chosenWeaponData
                    chosenWeaponsUI[i].enabled = true;
                    chosenWeaponsUI[i].sprite = chosenWeaponsData[i].image.sprite;
                }
                else
                {
                    //if null disable the correspoding element in chosenWeaponUI
                    chosenWeaponsUI[i].enabled = false;
                }
            }
    
            //assign chosen passive item data to chosenPassiveItemUI
            for (int i = 0; i < chosenPassiveItemsUI.Count; i++)
            {
                //check the sprite of the correspoding element in chosenPassiveItemData is not null
                if (chosenPassiveItemsData[i].image.sprite)
                {
                    //enable the corresponding in chosenPassiveItemUI and set it sprite to the corresponding sprite in chosenPassiveItemData
                    chosenPassiveItemsUI[i].enabled = true;
                    chosenPassiveItemsUI[i].sprite = chosenPassiveItemsData[i].image.sprite;
                }
                else
                {
                    //if null disable the correspoding element in chosenPassiveItemUI
                    chosenPassiveItemsUI[i].enabled = false;
                }
            }
        }
    
        void UpdateStopWatch()
        {
            stopwatchTime += Time.deltaTime;
    
            UpdateStopWatchDisplay();
    
            if (stopwatchTime >= timeLimit)
            {
                playerObject.SendMessage("Kill");
            }
        }
    
        void UpdateStopWatchDisplay()
        {
            int minutes = Mathf.FloorToInt(stopwatchTime / 60); //FloortoInt (round up to the nearest int)
            int seconds = Mathf.FloorToInt(stopwatchTime % 60);
            stopwatchDisplay.text = string.Format("{0:00}:{1:00}", minutes, seconds);
        }
    
        public void StartLevelUp()
        {
            ChangeState(GameState.LeveUp);
            if (levelUpScreen.activeSelf) stackedLevelUps++;
            else
            {
                Time.timeScale = 0f;
                levelUpScreen.SetActive(true);
                playerObject.SendMessage("RemoveAndApplyUpgrades");
            }
    
        }
    
        public void EndLevelUp()
        {
            Time.timeScale = 1f;
            levelUpScreen.SetActive(false);
            ChangeState(GameState.Gameplay);
    
            if (stackedLevelUps > 0)
            {
                stackedLevelUps--;
                StartLevelUp();
            }
        }
    }
    

    MissingReferenceException: The object of type ‘UnityEngine.RectTransform’ has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <c01a2e87500f4b88b40eba7308bfcbe6>:0) UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <c01a2e87500f4b88b40eba7308bfcbe6>:0) UnityEngine.Transform.set_position (UnityEngine.Vector3 value) (at <c01a2e87500f4b88b40eba7308bfcbe6>:0) GameManager+<GenerateFloatingTextCoroutine>d__35.MoveNext () (at Assets/Scripts/GameManager.cs:139) UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <c01a2e87500f4b88b40eba7308bfcbe6>:0) UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

    #18409
    Alp Apustaja
    Level 9
    AI Assistant
    (BETA)
    Helpful?
    Up
    0
    ::

    In the GenerateFloatingTextCoroutine method, add a null check for rect before attempting to modify its position:

    while (t < duration)
    {
        tmPro.color = new Color(tmPro.color.r, tmPro.color.g, tmPro.color.b, 1 - t / duration);
    
        if(target)
        {
            yOffset += speed * Time.deltaTime;
            if (rect != null) // Add this null check
            {
                rect.position = referenceCamera.WorldToScreenPoint(target.position + new Vector3(0,yOffset));
            }
        } 
        else
        {
            // If target is dead, just pan up where the text is at.
            if (rect != null) // Add this null check
            {
                rect.position += new Vector3(0, speed * Time.deltaTime, 0);
            }
        }
        yield return w;
        t += Time.deltaTime;
    }

    This modification will prevent the MissingReferenceException by checking if rect is not null before attempting to modify its position.

Viewing 7 posts - 1 through 7 (of 7 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: